Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!