NLAnaconda
NLAnaconda

Reputation: 1595

Styled Components in React, finding the corresponding component

Pretty new to styled components and I am liking it. However when building a React app I get ofcourse a lot of elements in the DOM. Sometimes I see a style that needs to be changed. But because the tag is something like:

<div class="kOs1nAz">content</div>

I have a hard time finding to which component this tag belongs to.

What is the best way to debug/find these styles inside your components? Maybe is there a way to prefix the classname with the component name or something like that?

Upvotes: 2

Views: 3385

Answers (3)

Aprillion
Aprillion

Reputation: 22322

If you have access to webpack config, add following plugin, as suggested by Better debugging:

{plugins: [['babel-plugin-styled-components', { displayName: true }]]}

If you use create-react-app, you might need react-app-rewired to modify webpack config.


If neither is a good option for you, you can switch from the browser inspector tool to React Dev Tools for Chrome or Firefox.

There, look up the tree until you see the name of your component (not styled-component, just the parent component that you export from your file) - that will help you identify which file to look in. Then, use the picker tool to select the relevant styled component inside (e.g. styled.button) and look at the structure of elements to help you locate it inside that file.

If you need to debug in a Production build, make sure to use displayName:

 const MyComponent = ...
 MyComponent.displayName = 'MyComponent'
 export default MyComponent

That will avoid minified names like t. If you have to debug before having a chance to add readable displayNames, then you will have to rely on DOM elements class attribute for elements where you added a className manually, or check names of props inside React Dev Tools to identify the elements...

Upvotes: 0

R Ganesh
R Ganesh

Reputation: 102

You can solve that using this babel-plugin

Basically it adds the name of the styled component to the list of classnames.

Hope this helps you.

Here are the docs if you need more information about this.

Upvotes: 0

kind user
kind user

Reputation: 41893

In your webpack config - babel plugin you have to set displayName to true:

['babel-plugin-styled-components', { displayName: true }]

The class names won't be shortened then.

Upvotes: 5

Related Questions