Reputation: 4322
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?
Upvotes: 6
Views: 1299
Reputation: 536
you can also give a className
to your styled
component.
you can achieve that by :
className
inside the components attributes
<Screen className="screen-component-className">...</Screen>
.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
:)
Upvotes: 1
Reputation: 3892
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.
Upvotes: 3