Styled components -> "as
" breaking styles!
If using as
renders a component without the desired styles, it is likely that you are using a styled component which extends another styled component. e.g.
const Element = styled.button`
/* this is the root styled element */
`;
const Button = React.forwardRef(({ children, ...rest }, ref) => {
return (
<Element ref={ref} {...rest}>
{children}
</Element>
);
});
const FancyButton = styled(Button)`
/* adding additional styles on top of <Button />! */
`;
// Then you're using it like this!
<FancyButton href='/' as="a">
some text
</FancyButton>
Many times when this happens what styled-component actually seeing is something along the lines of this...
const Element = styled.button`
/* this is the root element */
`;
const Button = React.forwardRef(({ children, ...rest }, ref) => {
return (
<Element ref={ref} {...rest}>
{children}
</Element>
);
});
const FancyButton = styled(as || Button)`
/* Replaces the component with what is provided by the 'as' */
`;
// Then you're using it like this!
<FancyButton href='/' as="a">
some text
</FancyButton>
The above is pseudocode and not exactly what is happening. You have many options to solve this, the best way is the styled-components built-in solution...
forwardedAs
is the solution, with one prop name change all is well.
<FancyButton href='/' forwardedAs="a">
some text
</FancyButton>