💅 Styled Components in React
Styled Components is a library for styling React components using tagged template literals. It enables writing actual CSS code within your JS and provides component-scoped styling.
📦 1. Installation
npm install styled-components
🎨 2. Basic Usage
Create a styled component using the styled
object:
import styled from 'styled-components';
const Button = styled.button`
background-color: #2563eb;
color: white;
padding: 10px 16px;
border: none;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
&:hover {
background-color: #1e40af;
}
`;
function App() {
return <Button>Click Me</Button>;
}
🌈 3. Dynamic Styles with Props
const Button = styled.button`
background-color: ${(props) => (props.primary ? '#4f46e5' : '#6b7280')};
`;
Now you can use <Button primary />
or <Button />
with different styles.
🌙 4. Theme Support
Styled Components supports theming with ThemeProvider
:
import { ThemeProvider } from 'styled-components';
const theme = {
colors: {
primary: '#2563eb',
text: '#111827',
},
};
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
✅ 5. Benefits of Styled Components
- No class name collisions (scoped styling)
- Dynamic styling via props
- Reusable styled components
- Supports theming out of the box