9 August 2019
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
-
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; } `;
-
Import it
import { css } from '../../../css/form.js';
-
Use it in render()....
return ( <Fragment> <style>{css}</style> <form onSubmit={this.handleSubmit} data-ys='form'> ... </Fragment> );
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');
-
Create the CSS file and save it as CSS (not as a template literal).
-
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') )