Server-side rendering with React.js

Server-side rendering with React.js


Let’s learn how to perform server-side rendering with React.js. To follow along, you’ll need node installed. First, open your Terminal. Then create a directory for the project– I’m going to name mine ‘React’– and let’s change into that directory. We’ll be using Express to build our web application, so install it with npm. Once that’s done, create a file named `server.js` and open it with your text editor of choice. First, require `express` and then instantiate the app. Next, create a route for the index page, which is designated by a forward slash. In the callback, it will respond with ‘Hello World!’ as the main heading. And we’ll specify port 3000 for our web server to listen on. I’m also going to log the base url to the console once the server has started. Let’s save the file and return back to our Terminal so we can start the server. Once it’s running, we can open the url in our browser. Also, I’m opening the ‘Developer Tools’ just for reference. Go back to your Terminal and press Control + C to stop your node server. So now let’s do some server-side rendering with React. First, we need to install the dependencies
`react` and `react-dom`. Once that’s done, let’s create our component file and open it with our text editor. For the time being, we won’t be using JSX because we’re only refactoring that one element. However, we’re still creating a React class
because we plan to add more to it later. Make sure to export the component, which returns a React element of ‘h1’ with no props and ‘Hello World!’ as the text. Let’s save our file and go to ‘server.js’. Here, we’ll require `react`, `react-dom/server`, and our component. We’ll update the html so ReactDOMServer renders our React element to a string. Save the file and start the server again. If you go back to your browser and refresh, you’ll notice that the page still looks the same. However, if you look at the ‘Elements’ panel in the ‘Dev Tools’, you’ll notice that there are data attributes that contain the word ‘react’. This proves that the React component was rendered on the page by the server. Now let’s add a few more things, like a paragraph and a button, to our component. Because there will be more going on, I’m going to use JSX because I find it more readable. However, node doesn’t understand JSX, so we’ll need a way to transpile them. We could create a build task that compiles the files before the server is started, or upgrade node’s require with Babel. We’ll do the latter so we don’t compile additional files. First, we must install `babel-register` and `babel-preset-react`. Once they’re installed, open `server.js` and at the very top, add the Babel require hook for the React preset. Now our component that’s required later will be transformed by Babel. Save the file and open `Component.jsx`. Here, we’ll refactor our component into JSX. We’re nesting our children in the root node ‘div’ because render can only return one node. Now let’s add back our heading. Following that, we’ll add a paragraph with some text. And finally, we’ll add a button that has an `onClick` event handler. The event handler will trigger an alert. Save the file and start your server again. Going back to our browser and refreshing, we can see the updated text as well as our button. However, when we click it, nothing happens. Where’s our alert? Well our app currently doesn’t have any client-side JavaScript because ReactDOMServer only renders the html markup. In order to make our app universal, we’ll need to build a JavaScript bundle that’s loaded on the client-side. Then our component will remount in the DOM and our JavaScript features will be present in the browser. We’ll cover that in the next video. But for this video, this is all it takes to setup server-side rendering with React.

34 thoughts on “Server-side rendering with React.js

  1. Let me know how make the app universal, please. I want to understand how to have a server-side react rendering plus javascript interaction in the browser with react method. Thanks a lot

  2. That you for explaining server side rendering in a very simple way! Please make the next video where my alert button works 🙂

  3. Hi, I built my website(ainoob.com) using React, but I didn't learn much about npm and node js stuff. Right now my website is using React and React Router, but I feel like there are so many code that cannot run on the server side, so is it still possible to make it isomorphic? Anyway, nice video.

  4. maannnn, thanks so much for your detailed explanation! just awesome! I was struggling like crazy because I was not creating a rootComponent with the whole html including the <html><body> tags

  5. I cannot thank you enough for this 3 part series on React server side. I spent hours on hours studying the docs, watching tutorials, and reading articles, but still couldn't get it. In 3 short videos you explained everything to me. Please don't change the style of your videos. The closeup black text on white background, the voiceover, and the use of vim creates a really clean vibe that sets you apart from almost all other dev tutorials I've seen.

  6. Thank you for your tutorial!
    Can you post videos to explain how to use Babel6 and webpack to do the server side bundling? I followed your tutorial and am trying to add ES6 syntax and some additional files which I need to import into server.js, but every time it gives error as "import xxx from 'xxxx' ", unrecognized keyword .

  7. Thanks for the quick and simple tutorial, was really helpful for me! Also liked the quality of the video! I might follow your example in my dev tutorials on my channel 🙂

  8. Hands down – best tutorial ive watched so far in my 20 internet years.
    really crisp, no errors, good speed – keep it up!

  9. When I try to change HTML this error occurs:

    "You're trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side"

    How can I fix it?

  10. Thank you for the tutorial, I have a question, it is not related to the tutorial but what external mouse are you using? or you're just using the Mac Trackpad?

    Thanks.

  11. Thank you for share this tutorials.

    I would like to see how to handle POST, PUT, DELETE request using universal javascript or Isomorphic express react applications.

  12. Great tut, love it. Not bloated with garbage, opinions or history of XYZ. Just a straight-forward example with a clean explanation. Commendable sir!

  13. Is this method deprecated? It's saying React.createClass is deprecated and will be removed in version 16.

  14. It's a great video I've ever seen. You are master of subject and the presentation! Kudos to you. Now, one question. Suppose my Component.jsx is not defining the entire document but another component say form and I have a separate index.html file with div with id='root' then what changes should I make to Component.jsx and server.js files ? Since, I am learning ReactJS (more interested in server side programming) I request your detailed explanation.

    I have also asked a question for the same on StackOverFlow at https://stackoverflow.com/questions/44534420/rendering-server-side-reactjs-component-on-client-side.

    Regards.

    Nizamuddin Shaikh, Ahmedabad, India.

  15. lol it's not server-side rendering… it's SSR only 50%. You didn't show how to render data in server-side… DISLIKE!

  16. Hello,

    After the edition mentioned at 2:19, when I start the server,
    and navigate to the page, I get the following error:

    > Warning: React.createElement: type is invalid — expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in.
    > Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in.
    > at invariant (/home/teodor/e/node_modules/fbjs/lib/invariant.js:44:15)
    > at instantiateReactComponent (/home/teodor/e/node_modules/react-dom/lib/instantiateReactComponent.js:74:56)
    > at /home/teodor/e/node_modules/react-dom/lib/ReactServerRendering.js:44:31
    > at ReactServerRenderingTransaction.perform (/home/teodor/e/node_modules/react-dom/lib/Transaction.js:143:20)
    > at renderToStringImpl (/home/teodor/e/node_modules/react-dom/lib/ReactServerRendering.js:43:24)
    > at Object.renderToString (/home/teodor/e/node_modules/react-dom/lib/ReactServerRendering.js:73:10)
    > at /home/teodor/e/start_here.js:19:30
    > at Layer.handle [as handle_request] (/home/teodor/e/node_modules/express/lib/router/layer.js:95:5)
    > at next (/home/teodor/e/node_modules/express/lib/router/route.js:137:13)
    > at Route.dispatch (/home/teodor/e/node_modules/express/lib/router/route.js:112:3)

    in general it reference the line in server.js file with React.createElement in :

    > app.get( '/', function( request, responce ) {
    > var html = ReactDOMServer.renderToString(
    > React.createElement( Component )
    > );
    > responce.send( html1 )
    > });

    if I replace it with

    > React.createElement( 'h1', null, 'Hello World!' )

    it work fine, can you help to understand what is the problem?

    Thank you in advance!

  17. Hey I wanted to render css with server side rendering…
    Can you please help me to achieve this…

    please help me out…

  18. Hi, i'm using a react app with a rails api. I wondering if a can user express too, but only to listen a redis server by socket.io. I expect figure out

Leave a Reply

Your email address will not be published. Required fields are marked *