Home > Blockchain >  How to dynamically change theme using StyledComponents?
How to dynamically change theme using StyledComponents?

Time:01-16

I have one whitelabel app and two end clients which want slightly different themes. I ideally do not want to have to pass the theme in at the top level and then through all the various components below.

  1. Is there a better way to do it?
  2. I would I dynamically select the theme?
  3. Can I make the theme globally available. Something like Tailwind CSS does with its config file and if so how to I dynamically change that?
<MyApp theme={theme}/> 

CodePudding user response:

You can make a separate file for styles like style.js and import the style from that file to any other file

CodePudding user response:

Here is a strategy you can use to accomplish this:

  • Make a component called ThemeProvider that contains your complete application. This part is in charge of maintaining the theme state and making it available to the rest of the program via the context API.
    import React, { createContext, useState } from 'react';
    
    export const ThemeContext = createContext();
    
    const ThemeProvider = ({ children }) => {
      const [theme, setTheme] = useState('light');
      return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
          {children}
        </ThemeContext.Provider>
      );
    };
    
    export default ThemeProvider;
  • To access the theme state and setTheme method across your application, utilize the useContext hook.

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';
import styled from 'styled-components';

const StyledButton = styled.button`
  background-color: ${props => props.theme.color};
`;

const Button = () => {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <>
      <StyledButton theme={theme} onClick={() => setTheme('light')}>
        Light
      </StyledButton>
<StyledButton theme={theme} onClick={() => setTheme('dark')}>
Dark
</StyledButton>
</>
);
};

export default Button;

  • At the top level of your application, include your "ThemeProvider" component and send the theme props to it.
import React from 'react';
import { ThemeProvider } from './ThemeProvider';
import MyApp from './MyApp';

const App = () => {
  return (
    <ThemeProvider>
      <MyApp />
    </ThemeProvider>
  );
};

export default App;

In this illustration, the context API is used by the ThemeProvider component to make the setTheme function and the current theme state available to the entire application. By invoking the setTheme function with the desired theme, the Button component can change the theme by accessing the theme state using the useContext hook and changing the theme.

  • Related