How to Use Styled Components in React: Simple Guide
styled-components in React, first install the package, then import styled from it. Create styled components by calling styled.tagName`css` and use them like regular React components in your JSX.Syntax
The basic syntax of styled components involves importing styled from the library and defining a styled element using template literals. You write CSS inside backticks after styled.tagName, where tagName is any HTML tag like div, button, or p. The result is a React component with styles scoped to it.
- styled.tagName: The HTML element you want to style.
- Template literals: CSS rules inside backticks
`...`. - Component usage: Use the styled component as a normal React component.
import styled from 'styled-components'; const StyledButton = styled.button` background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; `; function App() { return <StyledButton>Click me</StyledButton>; } export default App;
Example
This example shows how to create a styled button and a styled container. The button changes color on hover, demonstrating how to write CSS pseudo-classes inside styled components.
import React from 'react'; import styled from 'styled-components'; const Container = styled.div` display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; `; const Button = styled.button` background-color: #6200ee; color: white; padding: 12px 24px; font-size: 16px; border: none; border-radius: 8px; cursor: pointer; transition: background-color 0.3s ease; &:hover { background-color: #3700b3; } `; export default function App() { return ( <Container> <Button>Styled Button</Button> </Container> ); }
Common Pitfalls
Common mistakes include forgetting to install styled-components, not importing styled, or trying to use styled components without backticks. Another pitfall is writing invalid CSS inside the template literal, which will cause runtime errors or no styles applied.
Also, avoid using inline styles mixed with styled components for the same element, as it can cause confusion and override issues.
/* Wrong: missing backticks */ const WrongButton = styled.button( background-color: red; color: white; ); /* Right: use backticks for CSS */ const RightButton = styled.button` background-color: red; color: white; `;
Quick Reference
Here is a quick summary of how to use styled components:
| Step | Description |
|---|---|
| Install | Run npm install styled-components or yarn add styled-components |
| Import | Import styled from 'styled-components' |
| Create | Define a styled component: const Button = styled.button`css`; |
| Use | Use the styled component in JSX like <Button>Click</Button> |
| Style | Write normal CSS inside the template literal, including pseudo-classes |