How to Extend Existing styled-components Component?

You can extend an existing styled-components component using the styled() constructor/wrapper, for example, like so:

const ExtendedComponent = styled(MyComponent)`
  // ...
`;

To have a full picture, consider the following example:

const Button = styled.button`
  padding: 6px;
  border: none;
`;
const RoundedButton = styled(Button)`
  border-radius: 6px;
`;

This would make the RoundedButton component inherit the styling of the Button component, allowing you to add additional style rules and/or override existing ones.

You can use these buttons in your components as you normally would:

const Foo = () => (
  <>
    <Button>Original</Button>
    <RoundedButton>Extended</RoundedButton>
  </>
);

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.