CSS Emotion Library - Getting css props error when using css prop
As detailed in the Emotion documentation, use of the css
prop requires you replace React
with jsx
as the target function for JSX elements (known as the “pragma”), which will enable Emotion to intercept the css
prop and transform it into a className
prop for React.
For example:
<p>Hi</p>// Becomes the following by default:React.createElement("p", {}, "Hi")// But with the `jsx` pragma, it becomes:jsx("p", {}, "Hi")
There are two outlined approaches to achieve this. You only need to select one. If you are able to configure Babel in your application, the first is the recommended approach, but either one works fine:
Install a Babel plugin that will configure
jsx
as the default handler for all code in your appThe most direct way to do this is by adding the relevant Babel preset to your Babel configuration like so:
// Option 1A — Good// Add @emotion/babel-preset-css-prop to your dev dependencies, then// add the preset to your .babelrc configuration:{ "presets": ["@emotion/babel-preset-css-prop"]}
If you are able to do this, though, I recommend instead configuring babel-plugin-emotion, which includes the
css
prop configuration as well other features like minification, dead code elimination, and hoisting:// Option 1B — Better// Add babel-plugin-emotion to your dev dependencies, then add// the plugin to your Babel configuration (e.g. .babelrc){ "plugins": ["emotion"]}
Import the
jsx
function from Emotion and instruct Babel to use this imported function on a per-file basis using pragma/** @jsx jsx */import { jsx } from '@emotion/core'