Styling with props
- React course
- Beginner
- Lesson 58/84
- 4 min
Learn to pass a prop to a styled component to change its style.
Styling with props
styled-components can take props. Inside the template you produce dynamic values with ${props => props.color}.
So <Btn color="red" /> makes the button red. The same component works in different colors with different props.
This makes components reusable and flexible.
Conditional styling
You can also make styles conditional on props: ${props => props.primary ? "blue" : "gray"}. One component then works as both a primary and a secondary button.
This saves you from writing many class names; the logic sits in one place.
Later we will centralize colors with a theme; for now props are enough.
Practice Colored button
Complete the skeleton. Create a styled component ColorButton defined with styled.button\`color: ${props => props.color};\`. Return <ColorButton color="green">OK</ColorButton>. Export it.
Starter code
// Define ColorButton hereSample solution
const ColorButton = styled.button`color: ${props => props.color};`;
function App() { return <ColorButton color="green">OK</ColorButton>; }
export default ColorButton;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you access props in the template?
A dynamic value is made with a function inside ${}.- ${props.x}
- this.props.x
- props.x
- ${props => props.x} Correct answer
Explanation: Read props with a function inside ${}.
2 Styling with props: fill in the missing part
color: ${props => props.____};
color: ${props => props.color};
Explanation: You read the color via props.color.
3 Styling with props: match the terms
| Term | Meaning |
|---|---|
${props => ...} |
Dynamic value |
color="red" |
Passing a prop |
props.primary ? |
Condition |
<Btn /> |
Usage |