How to Extend Styles of React Component Using styled-components?

Add additional styles to an existing React component with styled-components

If you wish to style your own existing (or any third-party) React component, then you can simply use the styled-components' styled() constructor. This works as long as the React component you're styling attaches the passed className prop (or style prop, if you're using react-native) to the DOM element.

Consider for example the following unstyled Button component:

// Button.jsx
const Button = ({ className, children }) => (
  <button className={className}>
    {children}
  </button>
);

export default Button;

You can extend styling of this component with styled-components, for example, like so:

// PrimaryButton.jsx
import styled from 'styled-components';
import Button from 'Button';

const PrimaryButton = styled(Button)`
  color: white;
  background-color: blue;
`;

export default PrimaryButton;

You can use these buttons, for example, in the following way:

// Foo.jsx
import Button from 'Button';
import PrimaryButton from 'PrimaryButton';

const Foo = () => (
  <>
    <Button>Unstyled</Button>
    <PrimaryButton>Styled</PrimaryButton>
  </>
);

export default Foo;

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