Server Side Rendering, in Meteor, React, Material UI, Styled-components

I have implemented as explained in Meteor docs. All my components css which I have added gets rendered. But Material UI components, look and feel is not as I have in client version.

I have tried this MaterialUI Docs, but no luck yet. Also I’m not using react-jss .

If anyone knows any example projects, which I could use, that would be really awesome.

My Answer at StackOverflow

Follow the material-ui docs only, along with the meteor ones you are using. The only changes would be to use sink.appendToBody instead of the renderFullPage function.

So, something like this works:

server.js

onPageLoad((sink) => {
  const sheetsRegistry = new SheetsRegistry();
  const sheetsManager = new Map();
  const theme = createMuiTheme({
    palette: {
      primary: green,
      accent: red,
      type: 'light',
    },
  });

  const generateClassName = createGenerateClassName();

  const html = ReactDOMServer.renderToString(
    <div id='react'>
      <JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
        <MuiThemeProvider theme={theme} sheetsManager={sheetsManager}>
          <App />
        </MuiThemeProvider>
      </JssProvider>
    </div>
  )

const css = sheetsRegistry.toString();
sink.appendToBody(`<style id='jss-server-side'>${css}</style>`);
sink.appendToBody(html);

client.js

onPageLoad(() => {
	let div = document.getElementById('react');
	const jssStyles = document.getElementById('jss-server-side');
	if (jssStyles && jssStyles.parentNode) jssStyles.parentNode.removeChild(jssStyles);

	const theme = createMuiTheme({
		palette: {
			primary: green,
			accent: red,
			type: 'light',
		},
	});
	const generateClassName = createGenerateClassName();

	hydrate(
		<JssProvider generateClassName={generateClassName}>
			<MuiThemeProvider theme={theme}>
				<App/>
			</MuiThemeProvider>
		</JssProvider>,
		div,
	);
});
4 Likes

Yes, you are right. But my question has been not fully completed. Sorry my bad.
If you need to use styled-components together here, read this: Fully Explained Same Question

Glad that you figured it out!
The styled-components or any other thing can be used exactly as you were using before. For mui you have to simply add the generated css to the page on the server by using sheetsRegistry and remove it on the client.

1 Like