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' })` ... `;
Apart from helping you to scope styles, styled components include the following features: You can use standard CSS properties, and styled components will add vendor prefixes should they be needed. Styled components are independent of each other, and you do not have to worry about their names because the library handles that for you.
However, there are some drawbacks when you try to debug your styled components. In this article, I’ll introduce to you the pros and cons of building components with traditional CSS and styled-components.
With the React developer tools, it is also possible to view which components were responsible for rendering the selected component. Often this can be seen by looking at the component tree, but this is not always the case.
The styled object which is imported from styled-components, contains tons of HTML elements as methods that represent what the component is. For example, the button method above is a function that represents the HTML element "button". This means that the Button component is a button that can be used anywhere in our app just like any other component.
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!
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With