Search code examples
reactjstypescriptstyled-components

How to Identify React Styled Components in DOM?


I'm using Styled Components in React and I can create a component like so:

export const Screen = styled.div({
  display: "flex",
});

I then include it in my render code like this:

<Screen>...</Screen>

(where the ... above just represents other components).

However, when I look at the DOM, I have a hard time identifying my styled components from each other because their class names are just random strings: e.g. class="css-k008qs".

Is there any way to give the style components a name that will be seen in the DOM either in addition to or instead of the randomly generated class name?


Solution

  • you can also give a className to your styled component.
    you can achieve that by :

    • solution A on component render
      pass the className inside the components attributes
    <Screen className="screen-component-className">...</Screen>
    
    • solution B on component initiation
      add .attrs after your styled.div pass the className inside the components attributes
    const Screen = styled.div.attrs({
      className: "screen-component-className"
    })({
      display: "flex"
    });
    

    both methods will set a className to your styled components :)