How dynamically change ThemeProvider values in styled-components?

Viewed 515

In my projects I used some global css variables like --space-unit, --header-height and other. And it looked like this :

  --space-unit: 10px;
  --header-height: 70px;

  @media (max-width: 991px) {
    --space-unit: 7px;
    --header-height: 40px;
  }
  
  @media (max-width: 991px) {
    --space-unit: 5px;
  }

And for different screen resolutions, the variables were appropriate. how do I implement this with styled-components? That is, I create ThemeProvider, enter the initial values of spaceUnit and headerHeight in it, but how do I dynamically change it later?

1 Answers

You'll need to implement your own way of updating the theme as ThemeProvider does not provide this functionality.

You can use Context and wrap the existing ThemeProvider in your own provider that contains an updater function:

const ThemeContext = createContext();
const ThemeContextProvider = props => {
   const [theme, setTheme] = useState(LIGHT_THEME);
   return (
      <ThemeContext.Provider value={{ setTheme, theme }}>
          <ThemeProvider theme={theme}>
              {props.children}
          </ThemeProvider>
      </ThemeContext.Provider>
   )
}

Then in your app:

const App = () => {
    return (
        <ThemeContextProvider>
            <SomeComponent/>
        </ThemeContextProvider>
    )
}

const SomeComponent = props => {
    const { setTheme, theme } = useContext(ThemeContextProvider);
    return <div>hello there</div>
}
Related