Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

270
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The array dependence in useEffect hook not dispatch using window. For this you should use useLocation of react-router-dom.

I make this example https://codesandbox.io/s/custom-theme-provider-mui-based-in-routes-tt1d4 to resolve this problem.

const location = useLocation();
  const isMyLocation = location.pathname === "/MYlOCATION/PATH";

  useEffect(() => {
    if (isMyLocation) {
      setTheme(MyThemes.myother_theme);
    } else {
      setTheme(MyThemes.default);
    }
  }, [location.pathname, isMyLocation]);

Futhermore you need add BrowserRouter wrapper context in app for listening changes in state routes.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda