Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled components API - withComponent vs. as

I've stumbled upon a question regarding the Styled Component API updates in version 4:

  • withComponent which was handy to use, is now deprecated
  • as is the introduced alternative to it

But as far as I understood as is meant to be used on a JSX template level whereas withComponent was used within a styled component declaration.

So what is the suggested workflow in situations like following:

const BaseComponent = styled.div`
  color: red;
`;

const HeadingComponent = BaseComponent.withComponent('h4');

assuming that we use <HeadingComponent /> in a lot of different places.

Would it mean that instead of having a second styled component, declare a React component using the <BaseComponent as="h4" /> and instead of reusing the styled component, reuse the React component?

So transfer usage of withComponent into creating a new React component using the base styled component with as attribute?

Thanks in advance,

Andreas

like image 384
andi1984 Avatar asked Nov 16 '25 11:11

andi1984


2 Answers

While I personally prefer reusing the React component with the as prop, it could be easier for you to just refactor the usages into BaseComponent.attrs({ as: 'h4' })``.

like image 145
Václav Zeman Avatar answered Nov 18 '25 21:11

Václav Zeman


Instead of doing this:

const Anchor = styled.a`color: hotpink;`
const Span = Anchor.withComponent('span')

do this:

const styles = css`color: hotpink;`

const Anchor = styled.a(styles)
const Span = styled.span(styles)

styled-components v6 removed withComponent, so I expect this question to get a lot more attention.

like image 41
Gajus Avatar answered Nov 18 '25 20:11

Gajus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!