Introduction to Styled Components
Styled Components is a library for React and React Native that allows you to use component-level styles in your application. It enables you to write CSS that’s scoped to a single component and does not leak to any other element in the page.
Getting Started
To install Styled Components, run the following command:
npm install styled-components
Basic Usage
To create a simple styled component, you can use the styled
constructor as follows:
import styled from 'styled-components';
const Button = styled.button` background: #4caf50; color: white; border: none; padding: 10px 20px; font-size: 1rem; cursor: pointer;
&:hover { background: #45a049; } `;
function App() { return ; }
export default App;
Using Props
You can customize your styled components using props:
const Button = styled.button` background: ${props => props.primary ? '#6200ea' : '#03dac6'}; color: white; border: none; padding: 10px 20px; font-size: 1rem; cursor: pointer;
&:hover { background: ${props => props.primary ? '#3700b3' : '#018786'}; } `;
function App() { return ( <> > ); }
Extending Styles
You can extend the styling of another component using the .extend
method:
const TomatoButton = styled(Button)` background: tomato; &:hover { background: darkred; } `;
function App() { return Tomato Button ; }
Theming with Styled Components
Styled Components provides a ThemeProvider
to define and apply theming in your application:
import { ThemeProvider } from 'styled-components';
const theme = { colors: { primary: '#6200ea', secondary: '#03dac6', }, };
const Button = styled.button` background: ${props => props.theme.colors.primary}; color: white; border: none; padding: 10px 20px; font-size: 1rem; cursor: pointer;
&:hover { background: ${props => props.theme.colors.secondary}; } `;
function App() { return ( ); }
Animations
Styled Components also supports animations:
import { keyframes } from 'styled-components';
const rotate = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `;
const Rotate = styled.div` display: inline-block; animation: ${rotate} 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; `;
function App() { return < 🌎 > ; }
Explore these examples and refer to the styled-components
documentation for dozens of more useful APIs and examples.
Hash: b0d6a310c41936ea56cb4d2aa64c2d23ff8f36e3dc3037a1c216c979499d87dd