Prince Agrawal
Prince Agrawal

Reputation: 410

Styling a component passed by props with emotion in react

I am passing a component via props like:

const someicon = <SomeIcon>
..
<Sidebar icon={someicon} />

Then styling it with emotion/styled like:

const StyledIcon = styled(props.icon)`
  ...
`;

But the StyledIcon I am getting is a object:

{$$typeof: Symbol(react.forward_ref), defaultProps: undefined, __emotion_real: {…}, __emotion_base: {…}, render: ƒ, …}$$typeof: Symbol(react.forward_ref)defaultProps: undefinedrender: ƒ (props, ref)withComponent: ƒ (nextTag, nextOptions)__emotion_base: {$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}__emotion_forwardProp: undefined__emotion_real: {$$typeof: Symbol(react.forward_ref), defaultProps: undefined, __emotion_real: {…}, __emotion_base: {…}, render: ƒ, …}__emotion_styles: (4) ["label:StyledAppIcon;", "color:", ƒ, ";width:2em;height:2em;/*# sourceMappingURL=data:ap…1cblxuZXhwb3J0IGRlZmF1bHQgU2lkZWJhcjtcbiJdfQ== */"]displayName: (...)toString: ƒ value()get displayName: ƒ ()set displayName: ƒ (name)__proto__: Object

I can't figure out what is going on here and how to properly pass components via props, then style them and then render them.

Thanks

Upvotes: 0

Views: 2585

Answers (1)

Guerric P
Guerric P

Reputation: 31815

That's because styled-components only works for components so you have to pass the icon as a component (at least a function that returns JSX):

const someicon = () => <SomeIcon>

Also, you have to forward the className prop:

const someicon = ({ className }) => <SomeIcon className={className}>

If your icon component contains no more template than <SomeIcon />, then no need to wrap it, simply write this:

<Sidebar icon={SomeIcon} />

And make sure that the className is properly retrieved from the props and set on a DOM element inside the SomeIcon component, because styled-components works with classes under the hood.

Note: this is actually not a good practice to declare a styled component inside another component as it will be computed on every render cycle, and will display this warning:

The component Styled(icon) with the id of "sc-iqAclL" has been created dynamically. You may see this warning because you've called styled inside another component. To resolve this only create new StyledComponents outside of any render method and function component.

Upvotes: 1

Related Questions