andi1984
andi1984

Reputation: 676

Styled components API - withComponent vs. as

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

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

Upvotes: 3

Views: 3647

Answers (2)

Gajus
Gajus

Reputation: 73858

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.

Upvotes: 1

V&#225;clav Zeman
V&#225;clav Zeman

Reputation: 616

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' })``.

Upvotes: 6

Related Questions