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'
})`
...
`;
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!