In order to get started with React on the server side we're going to need a few things, so I'm going to install Express and React. Once we've got that installed I'm going to go ahead and create a file for our React component, it's going to be component.js, and I'm also going to create a setup file for our Express sever, express.js.
Here in our component we're going to create a component called component. That's just going to return react.createElement, we'll pass in an H1, this component won't have any props, and its inner HTML will be this.props.message. Since this is common js we're going to require React, and we're going to export our component. Cool. So let's jump over to our Express set up. Go ahead and bring in Express, bring in React, and finally we're going to bring in our component.
Our component's going to be wrapped in...oops, sorry. Component, our component is going to be wrapped in React.createFactory that's going to turn our component into a function that we can just pass our props into. Let's go ahead and instantiate our Express instance, and we'll go out and set that to listen on port 4000. Going to go up and set up a couple routes here.
Our empty route is going to resolve to a function called Home, we're also going to set up a route where we can pass in a parameter of message, and that will also resolve to Home, so let's go ahead and make that now. Going to be a function called Home, we'll get our request and our response in there. So we're going to set up this message variable to be equal to the parameter that's passed in, if it exists, otherwise we're just going to set it to "Hello."
Let's go ahead and instantiate our component, we're going to assign that to a variable called comp, and that will be component, and then we'll pass in our properties so this.props.message will be equal to message. Finally, we're going to output our component. Let's go ahead and save that, and get our Express server running. Cool. Let's try this out in the browser.
What we've got here is a JSON representation of our component, so the first way that we can get our component rendered properly is using react.renderToString. Try that out, and we have our component, and you can see that it's got all the react data attributes assigned to that element. We'll go ahead and pass in a parameter of "Hi," and cool. It's rendering all that out from the server.
Now the second method we can use if we want is render to staticMarkup. This is going to do the exact same thing with the minor exception that there is no react data attributes applied to it. So if we jump back here to Home we just get Hello, and it's in a pure HTML H1 tag.