20
votes

I am using styled-components in a React project. When the components are rendered in the browser they are assigned a randomly generated classname, for example:

<div class="sc-KSdffgy oPwefl">

This class name does not help me identify from which component the <div> came from, so is there a way to do this easily?

P.s. currently I am adding attrs to my styled components so that I can recognise them in dev tools, for example:

const Foo = styled.div.attrs({
   'data-id': 'foo'
})`
    ...
`;
5

5 Answers

33
votes

That's exactly why we created our Babel plugin, when using it you'll get class names that include the name you gave your component:

<div class="Sidebar__Button-KSdffgy oPwefl">

On top of that we set the displayName of the generated component too, which means in your React DevTools you'll see the actual component name rather than just <div> or <Styled(Component)>.

To use the Babel plugin install it with npm install --save-dev babel-plugin-styled-components and then add it to your Babel configuration: (e.g. in your .babelrc)

plugins: ["styled-components"]

That's it! Happy debugging 😊


Note that if you're using create-react-app you cannot change the Babel configuration. I use and would recommend react-app-rewired to be able to change configurations without having to eject. We've also built react-app-rewire-styled-components which automatically integrates the styled-components Babel plugin for you!

9
votes

For anyone using create-react-app, just substitute

import styled from "styled-components";

to

import styled from "styled-components/macro";

this will make your styled-component classes have the name of their component in them. And you'll be able to know which classes refer to which components just by looking at their class name ;)

6
votes

For anyone using create-react-app, another option is to use the styled components babel macro

  1. npm install --save babel-plugin-macros
  2. Inside your component use import styled from 'styled-components/macro'; instead of import styled from 'styled-components';

You should now see the component name in your dev tools:

enter image description here

3
votes

I was looking at doing the same and stumbled on the following as an alternative to attrs:

const Section = styled.div`
  background-color: #06183d;
  color: white;
  padding: 16px;
  margin-top: 16px;
  ${breakpoint("md")`
    border-radius: 5px;
  `}
`

Section.defaultProps = {
  "data-id": "Section"
}

Use React.Component's defaultProps. It keeps the call to styled.div cleaner and should be easier to remove if needed.

Results in: enter image description here

0
votes

If you use ts-loader or awesome-typescript-loader there is typescript-plugin-styled-components.