Carter
Carter

Reputation: 151

MUI React SSR issues

We are setting up Server Side Rendering for an existing project using React-MUI. We have gotten everything working except for styling. None of our CSS will load for the server side render. Any inline CSS works fine, but any of the sheets defined at the start of the file, and bound with export default withStyles(styles)(Page) do not work.

Our styling is defined as follows:

const styles = (theme) => ({ 
    root{
        //some CSS Here ...
    }...
});

Which is then bound to pour props with

export default typeof window !== 'undefined'
    ? withRouter(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(Home)))
    : withStyles(styles)(Home);

and accessed with

const {classes} = this.props;
//then in render
<div className={classes.root}>...</div>

None of the classes.someClassName CSS works in server side rendering, but the second we render in browser it functions normally. Current ideas are to try using a <ThemeProvider/> wrapper from MUI but any advice is appreciated.

Thanks!

Upvotes: 6

Views: 2539

Answers (1)

Carter
Carter

Reputation: 151

Thanks to @ReedDunkle for the pointers on this. Ended up getting it working by using his linked guide as a reference. I ended up only needing to add sheets.collect(...) as well as css = sheets.toString() and then including the CSS in the header of the HTML doc. No need for the ThemeProvider, it all linked up fine using WithStyles now.

So basically it looks like:

const html = renderToString(sheets.collect(<App/>));

const css = sheets.toString();

//...
//In your SSR HTML

<head>
<style id="jss-server-side">${css}</style>
...
</head>
...
<div id=react-root>{html}</div>

Upvotes: 3

Related Questions