In this lesson, we are going to have a quick look at server-side rendering.
The server-side side rendering is when you want to render your React components on the server so that they're already rendered when the page loads first.
So we are going to look at how react_on_rails offers a very simple built in method to allow us to do that.
We can see this if we have a look at our React calendar appointments app. When we first load the app page and look at the console, then react_on_rails logs some basic information about what it's rendering.
And then, when we look at the elements, we can see that there are a couple of hidden divs that react_on_rails adds. They specify what component we're going to render and all the data that is associated with the component. In our appointments app example, we have the appointments component, and then the props (the appointments data) passed to that.
Now, this is only getting rendered, after page load. This div is not populated until after page load.
Now, if we were to render it on page load, we can do that by going to our view file, where we are using our React component helper, and adding another attribute in the code, called prerender, and setting its value to true. It is set to false by default in react_on_rails.
So now if I go back to the app and refresh the page, you'll see that inside the appointments component, we now have these data-reactid attributes.
These are added when we render the component on the server. They weren't there when we had pre-render set to false, but they've been added when we pre-rendered the component on the server.
So that's a very simple way which react_on_rails gives us to pre-render our components on the server.
This attribute prerender is set to false by default. So if you don't specify it, that means server rendering is disabled. Now, typically, that's what we want to do. Only on certain pages, for example on public-facing pages for SEO reasons, we may want to pre-render them.
If you want to set this attribute globally to false or true, then you can do that in the react_on_rails initializer file.
If you go to config/initializers/react_on_rails.rb, there is a setting there, config.prerender = false. If you set it to true, your components will always render on the server.
Briefly, that is server-side rendering in react_on_rails. We'll look at it in more detail when we build some more examples where we'll use it.
This lesson was part of the The Complete React on Rails 5 Course.