Comments

React Server Side Rendering

React Server side Rendering, SSR, in short, is the place a frontend structure can render while running on a backend framework.

Applications that can render both on the server and the client side are called Universal Apps.

Why React Server-Side Rendering?

In contrast to client-side rendering, engineers pick SSR for two primary reasons:

  • Better execution
  • Better and predictable SEO execution

Difference between CSR & SSR

The first contrast among CSR and SSR is that for SSR, the server reacts with an HTML that is prepared to be rendered on the program. CSR then again, reacts with a report that contains connections to the JavaScript. In this way, the program will initially need to download the JavaScript, and it will it have the capacity to show the page.

Beginning

Like some other React venture, we will start by making another undertaking registry in our framework. So, open an order terminal, and create another React venture catalog utilizing the create-react-app direction.

React and Dependencies

$ create-react-app react-ssr
$ cd react-ssr

This order will create another organizer in your framework named React-SSR And fill it with the minimum necessities that will enable us to begin with our app.

We additionally need to introduce a couple more conditions, for example,

  • express: An insignificant and adaptable Node.js web app system that gives a great arrangement of highlights for web and versatile applications.
  • material-UI: A library made up of React parts that execute Google’s Material Design.

Tip

Use Bit to transform your React part into reusable “Lego pieces.” Every segment can be shared, created and matched up in the entirety of your venture, and every one of your parts is composed in a visual accumulation for your group. Attempt it.

  • Alongside these, we will likewise need to introduce next as a reliance. So let’s do that utilizing NPM/Yarn.
yarn add express material-ui next

Next Scripts

Once these are introduced, we will revise a portion of the scripts in a package.json record with the goal that they are utilizing next rather than the default react-scripts.

"scripts": {
 "dev": "next",
 "start": "next start",
 "build": "next build"
 }

Utilizing Next

An extraordinary thing about Next is that it realizes that our App is using React. So, we don’t have to import the library in our records. To demonstrate how this function, we can erase the whole src organizer and create an index.js inside another envelope named pages record with the accompanying code inside it:

const Index = ({ message= 'Hello World' }) =>       
   <div>         
     <h2>{message}</h2>     
   </div>;
 export default Index;

If you execute the npm run dev, you will see next beginning an improvement server for us and launching the above code on localhost:3000.

Wanna know another cool thing about Next? It likewise creates courses for us!

How about we create another record inside the pages organizer named star.js and compose the accompanying code inside it:

const Star = ({ dialogue = "I am a Star!" }) =>
   <div>
     <h2>{dialogue}</h2>
   </div>;
 export default Star;

If we append /star to the URL, we will see that Next has just accumulated and conveyed the new .js document as another page.

Custom Material-UI Theme

We should create another envelope in the venture’s root catalog named shared. This envelope is hold all the auxiliary code, beginning with our custom Material-UI subject. Inside the shared folder, create another organizer named MUI (short for Material-UI).

$ mkdir shared
$ cd shared
$ mkdir MUI
$ cd MUI

Next, we will create a record inside the MUI organizer named theme.js. Inside this document, we will characterize a portion of the essential hues that we will use all through our app.

export const PRIMARY_COLOR = "#ed1d24";
export const PRIMARY_COLOR_TWO = "#9c7e7e";
export const PRIMARY_COLOR_THREE = "#e1bdbd";
export const ACCENT_COLOR_ONE = "#2b1256";
export const ACCENT_COLOR_TWO = "#ffae5b";
export const ACCENT_COLOR_THREE = "#ff6a6a";

With our essential hues characterized, allows another document named customMUI.js. This record is going to hold a React Higher Order Component. A Higher Order Component is a segment that takes another part and infuses some usefulness inside it.

import React, {Component} from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Head from 'next/head';
import {
 PRIMARY_COLOR,
 PRIMARY_COLOR_TWO,
 PRIMARY_COLOR_THREE,
 ACCENT_COLOR_ONE,
 ACCENT_COLOR_TWO,
 ACCENT_COLOR_THREE
} from './theme';

material-UI contains a capacity named getMuiTheme that we are going to use to create our custom topic dependent on the shading esteems that we had characterized in theme.js record. We additionally need to ensure that the app that we are building loads a similar code on a server and the customer.

example

We will begin by making another const named customMaterialUI and characterize the HOC inside it. Inside this HOC, we will utilize the getInitialProps lifecycle snare that is given to us by Next. getInitialProps give us a userAgent from the application’s condition.

const customMaterialUI = ComposedComponent => {
   class HOC extends Component {
     static async getInitialProps(ctx) {
       const {req} = ctx;
       const userAgent = req ? req.headers['user-agent'] : navigator.userAgent;
       const subProps = await ComposedComponent.getInitialProps(ctx)
       return {
         ...subProps,
         userAgent
       };
     }
   }
 }

What’s going on here is that we are getting the user agent from either the server’s headers or if the app is running on a customer, we are bringing the user agent from the guide object. From that point onward, we are making a consistently named subProps.

By utilizing async await, we can hang tight for the ComposedComponent’s props. When we get those props, we have to restore the userAgent and the …subProps inside the HOC’s render work.

example

Next, we will take a shot at the HOC’s render. We will utilize the getMuiTheme that we had imported from the material-UI library.

render() {
   const {userAgent} = this.props;
   const Lato = 'lato, sans-serif';
   const muiTheme = getMuiTheme(
     {
       fontFamily: Lato,
       palette: {
         primary1Color: PRIMARY_COLOR,
         primary2Color: PRIMARY_COLOR_TWO,
         primary3Color: PRIMARY_COLOR_THREE,
         accent1Color: ACCENT_COLOR_ONE,
         accent2Color: ACCENT_COLOR_TWO,
         accent3Color: ACCENT_COLOR_THREE
       },
       appBar: {
         height: 30
       }
     },
     {
       userAgent
     }
   );
   return;
 }}

The more significant part of this is essential. We are setting the Font Family to Lato, and characterizing the Palette with our six hues from theme.js. Alongside that, we are setting the stature of our appBar to tallness of 30. At long last, we have to go to the userAgent const that we get from our props.

One final thing left to do here is the HOC’s arrival that is right now unfilled. Here, we will compose an ordinary HTML record that we see all over. It will have a Head section which will have a connection to the Google APIs to get the Lato Font Family. Just thing distinctive here is that rather than a Body, we will use the MuiThemeProvider segment that we had at first imported from the material-UI library.

MuiThemeProvider will fold over our ComposedComponent and will be passed the muiTheme that we just created.

return (
   <div>
     <Head>
       <title>Server Side Rendering in React</title>
       <meta name='viewport' content='initial-scale=1.0, width=device-width' />
       <link href='https://fonts.googleapis.con/css?family=Lato' rel='stylesheet' />
     </Head>
     <MuiThemeProvider muiTheme={muiTheme}>
       <ComposedComponent {...this.props} />
     </MuiThemeProvider>
   </div>
 );

Rendering Material-UI

In the last area, we created a custom UI Theme for our app utilizing Material-UI. In any case, on the off chance that we investigate our program, we will see that nothing has changed.

That is because we have just created the Theme despite everything we need to add the topic to our app.

We should perceive how to do this by making a header part for our app. In our venture’s root index, create another envelope called component with a header.js record inside it.

$ mkdir components
$ cd components
$ touch header.js

We should begin keeping in touch with some code for this part. Begin by bringing in the AppBar from material-UI. I will use this AppBar to create the Header part as appeared as follows:

import AppBar from 'material-ui/AppBar';
 const Header = ({title = 'SSR in React'}) =>
   <AppBar title={title} />
 export default Header;

With that our Header Component is prepared to be rendered inside the pages/index.js record. We should refresh the code over yonder so it utilizes this part.

import Header from '../components/header';
 const Index = ({title='SSR inside React'}) =>
   <div>
     <Header />
   </div>;
 export default Index;

In any case, to make this all work, we likewise need to import our HOC from the common/MUI/customMUI.js.

import customMaterialUI from '../shared/MUI/customMUI';

We likewise need to refactor the export statement with the goal that it uses customMaterialUI to infuse the Material-UI topic into our app.

export default customMaterialUI(Index);

End?

While React server side rendering may look basic enough, when building up the application you have to keep an eye out for a few points, which probably won’t be at first clear.

In case you’re using a react switch (for example @reach/switch or react-switch) you have to ensure that the correct URL is passed to the application when it’s rendered on the server — be beyond any doubt to check the best possible documentation!

Call to action

If you want to become a React master, check out Mosh’s React course. It’s the best React course out there!

Krissanawat is Nomad Web developer live in Chiangmai passionate on React and Laravel
Tags: , ,

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts