2

I have a very basic Node.js + Express app doing some server and client side rendering using React. When the Express app returns a React rendered component as a part of its response it comes back to the client with the CSS not applied. Then it quickly flashes to the CSS rendered page. I am kind of stumped as to what is happening and just want the CSS to be rendered immediately... I am kinda new to using webpack & React so any help/explanation will be greatly appreciated.

index.jade

html  
head
    title="Sample app"
    meta(charset='utf-8')
    meta(http-equiv='X-UA-Compatible', content='IE=edge')
    meta(name='viewport', content='width=device-width, initial-scale=1')
body
    #app!= content
    script(src='http://localhost:8080/public/index.js')

App.js

if (process.env.BROWSER) require("../styles/App.scss");

import React from 'react';

export default class App extends React.Component {  
  render () {
    return (
      <div>
        <p>Hello, world!</p>
      </div>
    )
  }
}

server.js (snippet)

...
app.get('/*', function (req, res) {  
    let content = React.renderToString(<App />);
    res.render('index', { content: content });
});
...

1 Answer 1

2

Use Extract Text Plugin to avoid flash of unstyled text. Pete Hunt (one of the creators of React) ran into this same issue with Webpack. From that, sokra (the Webpack developer) created this plugin to extract css into a stylesheet.

Without this plugin, the browser executes things in this order:

  • Show html (rendered by server-side React).
  • Get Webpack bundle.
  • Execute Webpack bundle which inserts style elements in head.

With this plugin, the browser executes things in this order:

  • Load stylesheets in head.
  • Show html (rendered by server-side React).
  • Get Webpack bundle.
  • Execute Webpack bundle.
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm! Thanks for the background too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.