CodeBlanks Logo Icon CodeBlanks

Using themes

Learn to share theme values across components with ThemeProvider.

Using a theme

A theme gathers colors and sizes into one object and offers it to the app. You wrap with ThemeProvider; children read values through props.theme.

Example: theme {primary: "blue"}; in the template color: ${props => props.theme.primary}. When the theme changes, everything updates.

Dark/light mode is easy with this structure.

ThemeProvider

You wrap ThemeProvider at the top of the app: <ThemeProvider theme={myTheme}><App /></ThemeProvider>. All styled components inside see the theme.

Keeping the theme object in its own file is clean; you change colors from one place.

This structure is the basis of consistent design systems.

Practice Themed button

Complete the skeleton. Create a styled component ThemedButton defined with styled.button\`color: ${props => props.theme.primary};\`. Export it.

Starter code

App.jsx
// Define ThemedButton here

Sample solution

App.jsx
const ThemedButton = styled.button`color: ${props => props.theme.primary};`;

export default ThemedButton;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you read a theme value in a template?

App.jsx
ThemeProvider provides props.theme.
  • props.theme.x Correct answer
  • this.theme
  • theme.x
  • window.theme

Explanation: Read it through props.theme.

2 Using themes: fill in the missing part

Question
color: ${props => props.theme.____};
Answer
color: ${props => props.theme.primary};

Explanation: You read the primary color via theme.primary.

3 Using themes: match the terms

Term Meaning
ThemeProvider Theme provider
props.theme Theme access
theme={x} Passing theme
{primary: "blue"} Theme object

All lessons in Beginner