Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active August 9, 2019 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/3785a4a3a371a26e7903477426216100 to your computer and use it in GitHub Desktop.
Save dfkaye/3785a4a3a371a26e7903477426216100 to your computer and use it in GitHub Desktop.
Using CSS files in React/JSX

9 August 2019

Using CSS files in React/JSX

If you work with CSS-in-JS solutions and you need CSS features that CSS-in-JS can't provide — for example, @media rules and/or CSS custom properties (aka CSS variables) — here are 2 approaches to get them working in your React/JSX app.

Credit goes to https://stackoverflow.com/questions/27530462/react-jsx-style-tag-error-on-render#34200213

Tweet thread https://twitter.com/dfkaye/status/1159886173331812352

Inline <style> elements

  1. Create a css.js file containing CSS defined and exported as a template literal:

     /* exameple: css/form.js */
    
     export const css = `
     [data-ys=form] {
       background-color: aqua;
     }
     `;
    
  2. Import it

     import { css } from '../../../css/form.js';
    
  3. Use it in render()....

     return (
         <Fragment>
             <style>{css}</style>
             <form onSubmit={this.handleSubmit} data-ys='form'>
             ...
         </Fragment>            
     );
    

Compose CSS files from other files

You could compose css.js files from other css.js files, and export the css literal that way, too.

    import { layout } from '../../../css/layout.js';
    import { form } from '../../../css/form.js';
    import { button } from '../../../css/button.js';

    export const css = [layout, form, button].join('\n');

Links to CSS files

  1. Create the CSS file and save it as CSS (not as a template literal).

  2. Add a <link href='path/to/app.css' rel=stylesheet> tag in index.js, assuming you normally mount an <App> component with ReactDOM:

     ReactDOM.render(
         <div>
             <link href='path/to/app.css' rel=stylesheet>
             <App />
         </div>,
         document.getElementById('root')
     )
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment