Easily debug styled-components' random classes

<div class="sc-bdVaJa bDWFJH"></div>

Here’s a div with a random class name. What component is it? How on earth will find this component in my codebase? The randomly generated class names give me no hints and make it harder to debug.

Just in case you don’t know why those class names are unique. The reason for that is exactly what makes us not having to worry about name collisions. No need to struggle with bike shedding some BEM rules that the whole team has to be aware of and follow. It’s time and energy consuming and perhaps in the end somebody breaks the rule and slowly it gets out of bounds and … yes…

So those random class names both have pros and cons. But there’s a way to solve this disadvantage. It’s possible to add descriptive prefixes to the class names which will make debugging much easier. The how-to has even it’s own chapter in SC’s docs yet I’ve seen quite many developers that still aren’t aware of this possibility and include this as one of the reasons why SC is not their cup of tea.

Let’s say we’ve a component such as this one, Title being the only styled-component

React component <Title>

And this is how the DOM tree will look in the browser (not very descriptive)

React component <Title>

You can see when we’re using vanilla CSS, we see the class name, so we can easily find that class in our code and modify its styles. But when we use SC we get this random ljsdfjaasfdjlsf classname which can be confusing when we have more than one h1 SC component

###The solution

So if you don’t have a CRA app or an ejected CRA app, you only have to follow these guidelines

the file called .babelrc should normally be located in the source file of your project

If however you have a CRA app, you don’t have to do anything except when you import styled-components you write import styled from "styled-components/macro"; in every file that you write styled components, instead of just import styled from "styled-components";.

Now we can see more descriptive class names such as:

React component <Title> - dom tree

And the same, using React Developer Tools:

React component <Title> - react developer tools

instead of this as before:

React component <Title>

And voilà!

In some rare cases you might have some obstacles with your babel config. If so, at least it’s open source and you could share the solution with others or rely on the strong community of SC.

Get more tips in my almost monthly newsletter about CSS & React!