Extending and Composing Styled Components
What you'll learn: How to build new styled components on top of existing ones, inheriting their base styles while adding or overriding specific properties.
The Core Idea
Once you've created a styled component, you often need a variant—something that keeps most of the original styling but changes a few properties. Instead of copying all the CSS, you can extend the existing component using the styled(Component) syntax. This creates a new component that inherits all base styles and lets you layer additional styles on top or override specific ones.
Think of it like inheritance in object-oriented programming: your child component gets all the parent's styles "for free," then you only specify what's different.
How Extension Works
import styled from 'styled-components';
// Base button with default styles
const Button = styled.button`
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
background-color: blue;
color: white;
cursor: pointer;
`;
// Extend Button, inheriting all its styles
const PrimaryButton = styled(Button)`
background-color: green;
font-weight: bold;
`;
const DangerButton = styled(Button)`
background-color: red;
text-transform: uppercase;
`;
In this example, both PrimaryButton and DangerButton inherit padding, border, border-radius, color, and cursor from Button. They only override or add the properties they need to be different.
Composition Pattern
This approach encourages building a library of base components, then creating specialized variants:
const Card = styled.div`
padding: 1rem;
border-radius: 8px;
background: white;
`;
const HighlightedCard = styled(Card)`
border: 2px solid gold;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
`;
Key Takeaway: Use styled(Component) to extend existing styled components, inheriting their base styles while overriding or adding only what's different—creating reusable style hierarchies without duplication.