Home > Net >  How to Identify React Styled Components in DOM?
How to Identify React Styled Components in DOM?

Time:07-30

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. .

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?

CodePudding user response:

I suggest using babel-plugin-styled-components for this. Please follow this guide: https://styled-components.com/docs/tooling#babel-plugin

Another way could be to write your own wrapper for styled(). But you have to manually use it in a lot of places unless you want to fork Styled Components.

Without touching Styled Components lib, you may try:

function prefixComponentName(Component, prefix) {
   Component.displayName = prefix   Component.displayName ?? Component.name;
   return Component;
}

Then use it wherever you need it, e.g.

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

But IMO, babel plugin is the best if it suits you.

CodePudding user response:

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

  • Related