Skip to main content
Sheelah Brennan

How to Use the styled-components Babel Plugin with Create React App

When kicking off a new project last week, I decided to give styled-components a try.  Some of the benefits of CSS-in-JS libraries like styled-components are the co-location of component styles with their respective components and the ability to leverage JavaScript in writing style rules. I noticed the styled-components documentation recommended using their babel plugin to make debugging easier and support server-side rendering, but it wasn't clear how to get that working with a React application built with Create React App. Here's how I did that.

Create React App with styled-components Setup

  1. Create your React application using the latest version of Create React App: nothing new here! npx create-react-app your-app-name
  2. Install babel-plugin-macros: this is what lets you easily install Babel plugins into zero-configuration projects like Create React App:

    npm install babel-plugin-macros --save-dev

  3. Within your React component, import the styled-components Babel macro instead of import styled;:

    import styled from 'styled-components/macro';

  4. Confirm that the Babel plugin is working: Using your browser's dev tools (no React dev tools extension needed), inspect your React component and check that you can see the component's styled-component name and CSS classes, not just the CSS classes themselves. See the next section for screenshots.

Is it Working?

If the styled-components Babel plugin is working, you should see additional debugging info for every styled component that you create in your browser's dev tools.

Before:

styled-components without its Babel plugin
styled-components without its Babel plugin

After:

styled-components with its Babel plugin
styled-components with its Babel plugin

Resources

Kaitlin Moreno's article, “Thinking in styled-components”, is a great overview of how to best leverage styled-components in React component development.

Follow Me

Built with ♥ and Gatsby, hosted on Netlify

My new Skillshare course: Make Your Website Stand Out