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

Is there a way to manually trigger a re-render of all React components on a page generated using array.map?

Within my parent component (Game), I am rendering child components (Card) from an array. Additionally, there is a Menu component that triggers a callback to Game in order to change its state. When switching levels (via a button click on the Menu), I want a ...

Using MUI autocomplete with an array of objects will result in a flattened one-dimensional array

I am currently using the Autocomplete component with the following setup: <Autocomplete options={channels} autoHighlight multiple disableCloseOnSelect value={form.channel_ids} getOpti ...

Learn how to dynamically import and load components in VueJS while rendering a list

I am currently rendering a list. <div v-for="msg in messages"> <div v-if="msg.type==='component'"> <component v-bind:is="getComponent(msg.component)" :data="msg.data" :text="msg.text"></component> </div> ...

A Guide to Dynamically Updating Page Titles Using JavaScript in a Ruby on Rails Application

Every time I use Ajax to load a blog post on the webpage, I adjust the <title> to "My Blog - BLOGPOST_TITLE". It is worth mentioning that "My Blog - " also shows up in the application layout. My dilemma is, how do I inform my Javascript about the " ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...

What is the best way to vertically align the second row in a carousel using Tailwind CSS?

Currently, I am working on developing an up-and-down carousel with Tailwind CSS. However, I am encountering a challenge in aligning the elements in the second row of my grid. My main objective is to have these elements centered vertically within the grid. ...

What is the best way to inject child nodes into parent nodes without causing the view to shift to the location where the element is being

While I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom-most element as it loads instead of maintaining the current view. Ideally, it should start at the top of the screen and remain there without any sudden ...

Retrieve data from a ng-repeat variable within a controller

Below is the current code snippet: HTML <center><li ng-repeat = "x in items | orderBy: 'priority'"> <!-- color code priorities --> <span ng-style="cmplt" ng-class="{ red: x.type == &apo ...

Encountering error while processing order in React.js using Stripe

const processPayment = async () => { try { const paymentResponse = await stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardElement) } }); ...

Utilize React to selectively execute either Server-Side Rendering or Client-Side

My current website utilizes SSR (using nextJS) to display the landing page in the root directory. However, I am interested in having my create-react-app application displayed when a user is logged in, and revert back to showing the landing page when they a ...

What is the best way to transmit data via $router.push in Vue.js?

I am currently working on implementing an alert component for a CRUD application using Vue.js. My goal is to pass a message to another component once data has been successfully saved. I attempted to achieve this by passing the data through $router.push lik ...

Steps to activate checkbox upon hyperlink visitation

Hey there, I'm having a bit of trouble with enabling my checkbox once the hyperlink has been visited. Despite clicking the link, the checkbox remains disabled. Can anyone provide some guidance on how to get this working correctly? <script src=" ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

Send the values of the form variables as arguments

I am trying to integrate a webform (shown below) with a function that passes form variables. Once the user clicks submit, I want the username and password to be passed into a website login function: $.ajax( { url: "http://microsubs.risk.ne ...

Guide on smoothly transitioning between 2 points within a requestAnimationframe iteration

Would it be possible to acquire a library for this task, or does anyone have any suggestions for my psuedocode API? Inquiry: How can I create a function that accepts 4 parameters interpolate(start, end, time, ease) and smoothly transition between the sta ...

Learn how to use a function in Google Maps to calculate and display distances

I have a script obtained from this link here and I am trying to create a function that returns the distance. This is my current script: var calcRoute = function(origin, destination) { var dist; var directionsDisplay; var directionsService = ne ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

Failed to access properties of an undefined value (attempting to read 'rows')

const client = require('../../db') const express = require('express'); const app = express(); const cors = require("cors"); app.use(cors()); app.use(express.json()); //req.body app.listen(8670, ()=>{ console.log("Server is now ...

Tips for testing the website's color modifications?

I recently had the task of replacing 10 specific colors with new ones in my CSS files. I used the find and replace method to make the changes in over 300 places throughout all the files. Now, I need a way to test if all the color replacements were done c ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...