question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Simple SSR, not rendering CSS on client-side?

See original GitHub issue
  • I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

Material UI Next should render with css upon loading of bundle.js in browser.

Current Behavior

Initially the non-hydrated html document has the CSS. But as soon as bundle.js loads, the document loses its css. I was following https://material-ui-next.com/guides/server-rendering/, and have done the same thing months ago on previous material-ui@next version with no problems at all. To confirm that my webpack build is okay I even tried just doing a bare index.html & bundle.js and it renders correctly with css upon bundle.js load.

Steps to Reproduce (for bugs)

  • /src/App.js
import React from "react";
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
class App extends React.Component {
  render () {
    return (
      <div>
        <Typography variant="display2" gutterBottom>
          Hello world
        </Typography>
        <Button variant="raised" color="primary">
          Hello World
        </Button>
      </div>
    );
  }
};
export default App;
  • /src/browser/index.js
import React from 'react';
import { hydrate } from 'react-dom';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { green, red } from '@material-ui/core/colors';
import App from '../App.js';
const theme = createMuiTheme({ palette: { type: 'light' } });
class Main extends React.Component {
  componentDidMount() {
    const jssStyles = document.getElementById('jss-server-side');
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
  }
  render() {
    return <App {...this.props} />
  }
}
hydrate(
  <MuiThemeProvider theme={theme}>
    <Main />
  </MuiThemeProvider>,
  document.querySelector('#root'),
);
  • /src/browser/index.js
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { SheetsRegistry } from 'react-jss/lib/jss';
import JssProvider from 'react-jss/lib/JssProvider';
import { MuiThemeProvider, createMuiTheme, createGenerateClassName } from '@material-ui/core/styles';
import { green, red } from '@material-ui/core/colors';
import App from '../App.js';
const app = express();
app.use(express.static('dist/browser'));
const theme = createMuiTheme({ palette: { type: 'light' } });
app.use((req, res) => {
  const data = { name: 'xemasiv' };
  const sheetsRegistry = new SheetsRegistry();
  const generateClassName = createGenerateClassName();
  const html = renderToString(
    <JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
      <MuiThemeProvider theme={theme} sheetsManager={new Map()}>
        <App />
      </MuiThemeProvider>
    </JssProvider>
  );
  const css = sheetsRegistry.toString();
  res.send(`
    <!doctype html>
    <html>
      <head>
        <title>xreact</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <style id="jss-server-side">${css}</style>
        <script src="/browser.index.js" defer></script>
      </body>
    </html>
  `);
});
app.listen(80);

Your Environment

Tech Version
Material-UI @material-ui/core: ^1.0.0-rc.1
React ^16.3.2
browser Version 66.0.3359.170 (Official Build) (64-bit)

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:3
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
simb4commented, Dec 3, 2018

Does this problem resolved? I’ve got same issue on production (on dev all works fine), html comes with css in it, but then strange thing happens: when client is loaded, everything become unstyled. After you try to focus on material button, it becomes styled again. Could someone provide some possible reasons? I’m using this boilerplate https://github.com/manuelbieh/react-ssr-setup client/index.js

import React from 'react';
import createHistory from 'history/createBrowserHistory';
import { hydrate } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router, routerMiddleware } from 'react-router-redux';
import App from '../shared/App';
import IntlProvider from '../shared/i18n/IntlProvider';
import { configureStore } from '../shared/store';
// material-ui
import JssProvider from 'react-jss/lib/JssProvider';
import {
  MuiThemeProvider,
  createMuiTheme,
  createGenerateClassName,
} from '@material-ui/core/styles';
import { palette } from '../shared/constants';

const browserHistory = window.browserHistory || createHistory();
const store =
    window.store ||
    configureStore({
        initialState: window.__PRELOADED_STATE__,
        middleware: [routerMiddleware(browserHistory)],
    });


class Main extends React.Component {
  // Remove the server-side injected CSS.
  componentDidMount() {
    const jssStyles = document.getElementById('jss-server-side');
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
  }
  render() {
    return <App />
  }
}


// Create a theme instance.
const theme = createMuiTheme({
  palette: palette,
  typography: {
    useNextVariants: true,
  },
});

// Create a new class name generator.
const generateClassName = createGenerateClassName({
  dangerouslyUseGlobalCSS: true,
});

hydrate(
    <JssProvider generateClassName={generateClassName}>
      <MuiThemeProvider theme={theme}>
        <Provider store={store}>
          <Router history={browserHistory}>
              <IntlProvider>
                  <Main />
              </IntlProvider>
          </Router>
        </Provider>
      </MuiThemeProvider>
    </JssProvider>,
    document.getElementById('app')
);

if (process.env.NODE_ENV === 'development') {
    if (module.hot) {
        module.hot.accept();
    }

    if (!window.store || !window.browserHistory) {
        window.browserHistory = browserHistory;
        window.store = store;
    }
}

server/render.js

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import IntlProvider from '../shared/i18n/IntlProvider';
import Html from './components/HTML';
import App from '../shared/App';
// material-ui
import { SheetsRegistry } from 'jss';
import JssProvider from 'react-jss/lib/JssProvider';
import {
  MuiThemeProvider,
  createMuiTheme,
  createGenerateClassName,
} from '@material-ui/core/styles';
import { palette } from '../shared/constants';


const serverRenderer = () => (req, res) => {
    // Create a sheetsRegistry instance.
    const sheetsRegistry = new SheetsRegistry();

    // Create a sheetsManager instance.
    const sheetsManager = new Map();

    // Create a theme instance.
    const theme = createMuiTheme({
      palette: palette,
      typography: {
        useNextVariants: true,
      },
    });

    // Create a new class name generator.
    const generateClassName = createGenerateClassName();

    const content = renderToString(
      <JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
        <MuiThemeProvider theme={theme} sheetsManager={sheetsManager}>
          <Provider store={req.store}>
              <Router location={req.url} context={{}}>
                  <IntlProvider>
                      <App />
                  </IntlProvider>
              </Router>
          </Provider>
        </MuiThemeProvider>
      </JssProvider>
    );

    const state = JSON.stringify(req.store.getState());
    const css = sheetsRegistry.toString();

    return res.send(
        '<!doctype html>' +
            renderToString(
                <Html
                    cssString={css}
                    css={[res.locals.assetPath('bundle.css'), res.locals.assetPath('vendor.css')]}
                    scripts={[res.locals.assetPath('bundle.js'), res.locals.assetPath('vendor.js')]}
                    state={state}
                >
                    {content}
                </Html>
            )
    );
};

export default serverRenderer;
0reactions
montoya332commented, Oct 28, 2021

@Vincz - any chance you found a solution to this . also using react-ssr-setup

Read more comments on GitHub >

github_iconTop Results From Across the Web

Simple SSR, not rendering CSS on client-side? #11410 - GitHub
I was following https://material-ui-next.com/guides/server-rendering/, and have done the same thing months ago on previous material-ui@next ...
Read more >
Why insert style again on client-side when using ssr? (from ...
SSR after all is for the initial loading of the page. So basically it is client rerendered to allow being dynamic.
Read more >
Client-side vs. Server-side vs. Pre-rendering for Web Apps
There's no question that user experience is impacted by perceived load times. With today's heavier front ends, client-side rendering doesn't feel very fast....
Read more >
Server Side Rendering (SSR) vs. Client Side Rendering (CSR ...
Client Side Rendering means generating the HTML components on the browser side, by executing Javascript code within the browser that manipulates the HTML...
Read more >
Server-Side Rendering (SSR) Vs Client-Side Rendering (CSR)
An application has a very simple UI with fewer pages/features · An application has less dynamic data · Read preference of the site...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found