One of the great things about React is the ability to easily share components between server and browser. In the following post I will demonstrate how to run the same exact React component server side and client side. The server used in this example is NodeJS/Express.
Typically there is a sharp divide between code running on the server vs code running on the client, but JavaScript based development lets us bridge this gap and share code between web server and browser easily.
My blog, SyntaxSuccess, is a hybrid website with SPA like features as well as server side pages. However, to create a consistent look I am sharing certain common elements between the different parts of the application. Ideally this should happen without code duplication, so I figured I'd give React a try and model the site's primary navigation as a shared React component. This means that parts of my site includes the primary nav as a client side component while other parts render the component from the server response.
It turns out that this is relatively straight forward since the component code, through the virtual DOM, is decoupled from the runtime environment. All you need is a little bit of plumbing in order to do the bootstrapping.
As you can see from the code below, the nav component is fairly straight forward:
Component defined in navigationDefinition.jsx
I am taken advantage of CommonJS patterns in order to expose the underlying React object.
Client side integration
The client side integration is easy and probably familiar to most developers with some React experience:
Note: You should run a compile time tool like browserify to convert the jsx into pure JavaScript before including it on your web page. If you're using Grunt you can add the following grunt task:
Server side integration
Wiring the component up for server side rendering using Express is also pretty straight forward
1) Install dependencies
2) Include dependecies
3) Create web endpoint and return the component as html
The component will now be returned as part of the page response.
To test the two modes of the left navigation just go to the following links:
Happy coding!