Server-side render does not render UI library

Viewed 896

I am trying to implement a server-side rendering for my app. It used to be a client side render using ReactDom. Everything works fine in client-side render, but now when I make it server-side render, none of the CSS sheet and UI libraries(Reactstrap + Material UI) are rendered. The UI broke completely.

I am injecting my App.js(actual front-end page with all the UI) into my html.js(a template)

My server:

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server'
import App from '../../src/App'
import Html from '../../src/html.js'
const app = express();

// console.log that your server is up and running
app.listen(3001, () => console.log(`Listening on port 3001`));

app.get('/',(req,res) => {
  const title="2FA SDK"
  const body = renderToString(<App/>)
  res.send(
    Html({
      body,
      title,
    })
  )
})

My html.js(just a simple template):

const Html = ({ body, styles, title }) => `
  <!DOCTYPE html>
  <html>
    <head>
      <title>${title}</title>
    </head>
    <body style="margin:0">
      <div id="app">${body}</div>
    </body>
  </html>
`;

My app.js(using material ui, minimal)

render(){
    return(
        <div className="container">
            <div>
                <TextField 
                    label="Application Name"
                    type="text" 
                    variant="outlined"
                    onChange={this.handleApplicationName}
                />
            </div>
            <div>
                <FormLabel>Phone</FormLabel>
                <div>
                    <OutlinedInput
                        value={this.state.textmaskArray[2]}
                        onChange={(e) => this.handlePhoneNumber(e,2)}
                        labelWidth={200}
                    />
                </div>
            </div>
            <Button variant="contained" color="primary" onClick={this.props.buttonAction}>
            </Button>
        </div>

Part of App.js that uses reactstrap:

render(){
    return(
      <CardControl
        title={"Code Authention"}
        message={"For your security, we need to verify your identity by sending a code to your phone number"}
        >
        <Container>
            <Row>
                <Col>
                    <div>{this.props.phoneList}</div>
                </Col>
                <Col>
                    <div>{this.props.methodList}</div>
                </Col>
            </Row>
            <Button className="sm-2" disabled={this.props.disabled} color="info" onClick={this.props.buttonAction}>{this.props.buttonName}</Button>
        </Container>
      </CardControl>

) } My webpack.config.js:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");

module.exports = [
    {
        /*Config for backend code*/ 
        entry: './src/server/server.js',
        target: 'node',
        output: {
            filename: 'server.js'
        },
        externals: [nodeExternals()],
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.html$/,
                    use: {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                },
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader,"css-loader"]
                }
            ]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename:"./index.html"
            }),
            new MiniCssExtractPlugin({
                filename: "[name].css",
                chunkFilename:"[id].css"
            })
        ]
    },
]

What I am using: Create-react-app

What I have tried: I installed CSS loders, but it is not working at all. I also looked up material-ui's document on server-side rendering, I feel like I am just missing a small part and the instruction they provided may be a overkill.

What I need help with: I am trying to figure out why the UI component from material-ui or bootstrap did not get render at all. I am suspecting that nodeExternal exclude them, but I am not sure.

1 Answers

You will need to hydrate your rendered HTML in the client side in order to have react take over.

Create a client.js file with:

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.hydrate(
  <App/>,
  document.querySelector('#app'),
);

note that the hydrate should match what renderToString rendered.

Next add this as an additional entry in your webpack configuration:

module.exports = [
{
        /*Config for backend code*/ 
        entry: './src/server/server.js',
        target: 'node',
        output: {
            filename: 'server.js'
        },
        externals: [nodeExternals()],
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.html$/,
                    use: {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                },
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader,"css-loader"]
                }
            ]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename:"./index.html"
            }),


  new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename:"[id].css"
        })
    ]
},
{ 
   entry: './client.js',
   output: {
      filename: 'bundle.js',
   },
   module: {
      rules: [ {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
      },
   ],
 },
]

Change your html rendering code to include this:

const Html = ({ body, styles, title }) => `
  <!DOCTYPE html>
  <html>
    <head>
      <title>${title}</title>
    </head>
    <body style="margin:0">
      <div id="app">${body}</div>
      <script async src="/bundle.js"></script>
    </body>
  </html>
`;

I'm not 100% confident on whether this exact code will work but this is the general idea.

Related