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

Render a different tag whilst keeping styled-components Styling

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>
);

Hope you found this post useful. It was published . Please show your love and support by sharing this post.