Skip to content

Instantly share code, notes, and snippets.

@JamesBliss
Created June 23, 2020 09:18
Show Gist options
  • Save JamesBliss/814c177d5b8fb0d7d2b6ee622162d96d to your computer and use it in GitHub Desktop.
Save JamesBliss/814c177d5b8fb0d7d2b6ee622162d96d to your computer and use it in GitHub Desktop.
forwardedAs like a boss

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>

See it in action...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment