How to Include Emotion Component Names in CSS Classes Under Create React App
I recently started a new React project using Create React App and Emotion, a CSS-in-JS library, for styling. The developer experience with Emotion has some benefits, including having component styles scoped and set directly in a component's Javascript file. One downside is that it can be difficult to identify your React components when looking directly at the resulting HTML markup in a browser devTools environment. The CSS classes generated are not human-readable, so a lot of components (especially those using divs) end up looking the same. This can make debugging difficult.
One solution is to install the React DevTools browser extension and use that to review the generated React component tree.
A solution that I prefer, in addition to heavily leaning on React DevTools, is to have Emotion generate CSS classes that include the component name. For example, instead of seeing a <List>
component get a generated class of css-11co5m7
, it would get a generated class like css-11co5m7-List
. Having the component name appended to the generated CSS class just feels nicer to me!
The normal solution for this is to use Emotion's babel plugin. However, there's not yet support for babel plugins in Create React App. Thankfully, there is another way to get this to work without ejecting from Create React App. Here's how you can get your component names included in CSS classes:
Install Emotion and Related Dependencies
You'll need to first install Emotion if it's not already installed:
npm i @emotion/react
I'm using the styled
syntax with Emotion, which is inspired by styled-components, so I also installed the library for that:
npm i @emotion/styled
Update Emotion Imports
The last step is to change all @emotion/styled
imports within your components to instead import @emotion/styled/macro
.
For example, given an import like this:
import styled from '@emotion/styled;
You would change that import to look like this:
import styled from '@emotion/styled/macro;
Verify Your Setup
Finally, take another look at your app running on your dev server and you should now see component names included in CSS classes. Hooray!
Featured image by Alex Mihis via Unsplash