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