Skip to content

Instantly share code, notes, and snippets.

@koistya
Last active September 10, 2016 16:26
Show Gist options
  • Save koistya/a495006ea9d27c567887 to your computer and use it in GitHub Desktop.
Save koistya/a495006ea9d27c567887 to your computer and use it in GitHub Desktop.
Collecting critical CSS from React.js components for pre-rendering on a server (SSR)

Which one of these two syntaxes do you prefer for pre-rendering critical CSS in ReactJS apps?

Example 1

import styles from './MyComponent.less';
import { withStyles } from '../decorators';

@withStyles(styles)
class MyComponent {
  render() {
    return (
      <div className={this.className()}>
        <div className={this.className('foo')}>Hello</div>
      </div>
    );
  }
}

export default MyComponent;

Example 2

import { withStyles } from '../decorators';

@withStyles
class MyComponent {
  static styles = require('./MyComponent.less');
  render() {
    return (
      <div className={this.className()}>
        <div className={this.className('foo')}>Hello</div>
      </div>
    );
  }
}

export default MyComponent;

Example 3

import { withStyles } from '../decorators';

@withStyles
class MyComponent {
  static displayName = 'MyComponent';
  render() {
    return (
      <div className={this.className()}>
        <div className={this.className('foo')}>Hello</div>
      </div>
    );
  }
}

export default MyComponent;

CSS Example

// MyComponent.less
.MyComponent {
  border: 1px solid red;
  &-foo {
    color: green;
  }
}

Server-side Rendering Example

server.get('*', (req, res) => {
  let title;
  let css = [];
  let html = React.renderToString(<App
    onSetTitle={val => title = val; }
    onInsertCss={val => css.push(val); } />);
  res.send(`
    <html>
      <head>
        <title>${title}</title>
        <style>${css.join('')}</style>
      <head>
      <body>
        <div id="app">${html}</div>
        <script src="/app.js"></script>
      </body>
    </body>`);
});

kriasoft/react-starter-kit#112

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment