How to easily inspect styled-components using dev tools?

Viewed 16278

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 Answers

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 ;)

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

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

Related