15. Aiming for Isomorphic

The last step for this project is to get our page into the “Isomorphic” functionality, where we render the page from the server but then let the client take over the server-rendered React components and update their state to re-render them. We have two components to use for this stage: HelloWorld and Timestamp. Let’s start with HelloWorld.

It’s been a while since we’ve looked at HelloWorld, let’s refresh our memories of what that component looks like.

var React = require('react')

module.exports = React.createClass({
  render: function() {
    return (
      <div>
        <div>
          This is from the HelloWorld.jsx
          component render function.
        </div>
        <div>
          Rendered from: {this.props.from}
        </div>
      </div>
    )
  }
})

Okay, cool - this component already has a placeholder for where it was rendered from. But it’s based on props, not state. Let’s convert it over to use state so that the client can more easily update it.

var React = require('react')

module.exports = React.createClass({
  getInitialState: function() {
    return { from: this.props.from }
  },
  render: function() {
    return (
      <div>
        <div>
          This is from the HelloWorld.jsx
          component render function.
        </div>
        <div>
          Rendered from: {this.state.from}
        </div>
      </div>
    )
  }
})

We now pass the property in the same way, but the property value gets converted over to state, which we can then modify later through setState(). Now let’s see what happens when we try to use this component on the client. We’ll simply add another <script> tag to get started.

<script src="/Components/HelloWorld.js"></script>

Running the page, we get an error in the console.

Uncaught ReferenceError: require is not defined

Dang. HelloWorld.js is using Node’s require and module.exports to register itself as a module. We skipped that in Timestamp.js, which is why it worked; the browser doesn’t support these constructs.

Next » Using Browserify