React styled-components v5 – how to use theme

As you apply css style to many components you will realize that you want to have

  1. consistent style to be applied to your web/mobile application
  2. easy way to change the style depending on some conditions

style-components provides an easy way for that – theme. You can define a theme which could be applied to the app globally.

Define a theme

This could be in separate files if you would like to have multiple themes. In this example, I defined two themes – light and dark – in separate files. I typically place the theme files under components/thems folder.

light.js
const theme = {
  id: 'light',
  primaryColor: '#f8049c',
  secondaryColor: '#fdd54f',
  bodyBackgroundColor: 'white',
  bodyFontColor: 'black'
}

export default theme;
dark.js
const theme = {
  id: 'dark',
  primaryColor: 'black',
  secondaryColor: 'midnightblue',
  bodyBackgroundColor: 'black',
  bodyFontColor: 'white'
}

export default theme;

Use the theme in the theme provider

Import ThemeProvider in styled-components and set the theme in App.js. As you can see in the example below, I am choosing the theme based on the id. The ThemeProvider now injects all the defined properties to all styled components under the App.js

import {ThemeProvider} from 'styled-components';
import LightTheme from 'themes/light';
import DarkTheme from 'themes/dark';


function App() {
    <ThemeProvider theme={{...theme, setTheme: () => {
      setTheme(s => s.id === 'light' ? DarkTheme : LightTheme) 
    }}}>
    
    // other code ...
}

In any styled components under the App.js, you can access the theme now.

const HeaderWrapper = styled.header`
  background-image: linear-gradient(
    to right,
    ${p => p.theme.primaryColor},
    ${p => p.theme.secondaryColor});
  border-bottom: 3px solid ${p => p.theme.secondaryColor};
`;

Leave a Reply

Your email address will not be published.