Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI v5 server side rendering css order not working with gatsby

I posted an issue here too: https://github.com/mui-org/material-ui/issues/25312

So, I'm using the Gatsby example that Material UI v5 has: https://github.com/mui-org/material-ui/tree/next/examples/gatsby

In the example they provide I then add this snippet of code:

import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles({
  typographyHeader: {
    fontWeight: 'bold',
    fontSize: () => 30,
    color: '#292929',
  },
});

<Typography classes={{ root: classes.typographyHeader }} align="center">
  Gatsby v5-alpha example
</Typography>

Here's the output when running npm run develop with js enabled (browser mode):

enter image description here

Here's the output when running npm run develop with js disabled (the same output as SSR):

enter image description here

You can see that in the second screenshot my custom styles have been overwritten by material ui's styles. The same issue happens when using withStyles as well.

Can anyone help me figure out the correct config so that my styles don't get overwritten for Material UI v5?

Thanks

like image 315
Martin Dawson Avatar asked Mar 15 '21 13:03

Martin Dawson


1 Answers

Posting the answer from the GitHub issue by MUI's founder because this will affect many many Gatsby users in the future.

@MartinDawson I had a look at your issue. I believe this problem can't be solved with the current API exposed by Gatsby and emotion. What we would need is the capability to extract the CSS output from the HTML page, and inline it in the initial SSR request, before the JSS output.

You have 3 options:

Stop using the makeStyles/withStyles API now. We are about to deprecate them in v5 (and remove in v6). Migrate to Next.js. Use styled-components instead of emotion. styled-components doesn't render it's style inside the body, with the order of the Gatsby plugins, you should be able to get the correct injection order.

This is correct from my findings, makeStyles and withStyles don't work with SSR and gatsby.

The best solution is to use the new sx prop. This can do everything that these functions can do anyway including media queries and use theme prop. The one downside is that it's slightly slower for many many uses.

See the docs here: https://web.archive.org/web/20210116082036/https://next.material-ui.com/system/basics/#the-sx-prop

And for any other edge cases you can use styledComponents API as that should work with it.

Update:

Check out this comment too: https://github.com/mui-org/material-ui/issues/25312#issuecomment-900163029

like image 166
Martin Dawson Avatar answered Oct 21 '22 14:10

Martin Dawson