'React.js use ThemeProvider based on route

Hi all as per title I would like based on the route to use a different theme provider my code looks like that:

const rootElement = document.getElementById('root');
 ReactDOM.render(
  <ThemeProvider theme="MyThemes.default">
      <CssBaseline />
       <App />

, rootElement, );

where

const myThemes= {
 default: createMuiTheme({ ...defaultTheme, ...typography, overrides: { ...muiCssBaseline, 
  ...muiTableOverrides } }),
 myother_theme: createMuiTheme({ ...myOtherTheme, ...typography, overrides: { 
 ...muiCssBaseline, ...muiTableOverrides } }),

};

so when i am in a particular route I want to use myother_theme

I was making a wrapper component to call in the index.js like that

const ThemeProviderChange = ({ children }) => {
 const [theme, setTheme] = useState(Themes.default);
 const isMyLocation= window.location.pathname === "/MYlOCATION/PATH"?? true;
 
 const url = window.location.pathname.split('/').pop();

  useEffect(() => {
    if (isMyLocation) {
     setTheme(MyThemes.myother_theme);
 
    } else {
     setTheme(MyThemes.default);
    }

   }, [url]);
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
   };

  export default ThemeProviderChange;

but to be working it requires the user to make a manual refresh. Any suggestions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source