How to Keep styled-components Styling but Render a Different Tag or Component?

If you wish to switch out the HTML tag (or a custom component) that's rendered whilst keeping all the styled-components styling you've applied to a component, then you can simply use the "as" prop (v4+) to do this at runtime.

Consider, for example, the following styled-components component:

const MyComponent = styled.div`
  color: white;
  background: blue;
`;

To render a <button> for example, instead of the <div> DOM element (as in the example above), you can use the as prop like so:

// styled-components 4+
const Foo = () => (
  <MyComponent
    as="button"
    onClick={() => alert('Hello world!')}
  >
    Foo
  </MyComponent>
);

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.