CodeBlanks Logo Icon CodeBlanks

Styling with props

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

App.jsx
// Define ColorButton here

Sample solution

App.jsx
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?

App.jsx
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

Question
color: ${props => props.____};
Answer
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

All lessons in Beginner