Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet:

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

, rootElement, );

Here is how the themes are set up:

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

So basically, I want to switch to 'myother_theme' when a specific route is accessed.

I tried creating a wrapper component in index.js like this:

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;
    

However, it seems that a manual refresh is required for it to work properly. Any suggestions on how to overcome this issue?

Answer №1

To solve the issue of array dependence in the useEffect hook not dispatching using window, you can utilize the useLocation hook from react-router-dom.

I have provided an example to address this problem: https://codesandbox.io/s/custom-theme-provider-mui-based-in-routes-tt1d4

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

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

Additionally, make sure to add the BrowserRouter wrapper context in your app to listen for changes in state routes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue causing "ReferenceError: fetch is not defined" is causing the test to fail

There seems to be an issue with my project where 'node-fetch' is installed, but the rest of the files are not importing it and the tests are not failing import { IQuery } from 'models/IQuery.interface'; import { NextApiRequest, NextApiR ...

GTM - monitoring the most recent clicked element's input data

Custom Script function() { var inputs = document.getElementsByTagName("input"), selectedRadios = []; for (var i = 0;i < inputs.length;i++) { if(inputs[i].type==="checkbox" && inputs[i].checked) { selectedRadios.push(inputs[i].value); ...

Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the ...

What are the best practices for integrating RxJS into Angular 2 projects?

How can I write code like this in Angular 2? var closeButton1 = document.querySelector('.close1'); var close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click'); I have attempted various methods to incorporate this into an An ...

What are the steps to resolve an invalid token error when receiving it? (repl.it)

Today marks my introduction to node.js, recommended by a friend. Due to limited resources, I have opted to utilize repl.it for hosting. However, I am faced with an error in my first attempt at using it. The purpose of my current script is to make my user ...

Is it possible to initiate a smart contract deployment directly from a website?

My goal is to deploy a smart contract directly from a webpage. Currently, I am using react for the frontend and have written a smart contract in solidity. However, the contract is only deployed when I run the truffle commands in my terminal. I am looking t ...

Setting up a Vercel deployment for a NX Monorepo project with React and Express

https://github.com/clearhost-cmd/helloapp I am facing challenges in deploying my NX Monorepo to Vercel. While the NX Monorepo runs smoothly on localhost without any issues, I'm encountering difficulties getting it to work on Vercel. There are no e ...

Can the inclusion of a type guard function impact the overall performance of the application?

const typeGuard = (param: any): param is SomeType => { return ( !!param && typeof param === "object" && param.someProperty1 !== null && param.someProperty2 === null ) } If a type guard function similar to the code above is exe ...

Setting state for a dynamic component based on condition in React

Working on creating a dynamic component where the data index matches the URL parameter blogID received from the router. Below are the router parameters sending props to the component: <Route path='/blog/:blogId/:blogTitle' render={() => & ...

Different ways to modify the underline and label color in Material-UI's <Select/> component

A while ago, I came across this useful demo that helped me change the colors of input fields. Here is the link: https://stackblitz.com/edit/material-ui-custom-outline-color Now, I'm on a quest to find a similar demo for customizing the color of selec ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

The Holy Alliance of Laravel and Vue

I am facing issues with user authentication using Laravel Sanctum. I have set up everything properly, with Vite and Vue 3 as the frontend. The problem arises when I attempt to login with Laravel's default auth - it works fine. However, when I make a r ...

Using jQuery to eliminate the 'disabled' attribute from CSS

After using the .val() method to enter data into a text box, I noticed that when trying to click "add", the button appears disabled. <input class="btn-primary action-submit" type="submit" value="Add" disabled=""> If I manually type in text, the dis ...

Is it possible to temporarily halt animation in react-transition-group while retrieving initial data within components?

I am working with the App component that looks like this: <Route render={( { location } ) => ( <TransitionGroup component="div" className="content"> <CSSTransition key={location.key} className ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Customize your error messages in AJAX requests

The form on my index.php page submits to process.php, triggering the execution of the code below: $(document).ready(function() { $('#login_button').click(function() { event.preventDefault(); var formData = { 'email' ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

Executing multiple ajax calls and retrieving the results: A step-by-step guide

I am looking to run a series of Ajax calls and collect the responses before rendering the results for the user. The current code I am using is not working as expected because the render function is being executed before all the Ajax responses have been ga ...

What is the best way to design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...