The issue with MUI createTheme lies in its failure to correctly communicate the theme to MUI components

After setting up a theme for my React.JS project using MUI in the index file, I encountered an issue when trying to style the Appbar. The theme does not seem to affect the menu button or the menu itself. The button appears as the default generic style, and the menu remains white instead of matching the color of the Appbar.

This is how my index.tsx file looks:

import React from "react";
import ReactDOM from "react-dom";
import AppbarTop from "./AppbarTop";
import { Router } from "react-router";
import { createBrowserHistory } from "history";
import AdapterDateFns from "@mui/lab/AdapterDateFns";
import { LocalizationProvider } from "@mui/lab";
import { createTheme } from "@mui/material";
import { ThemeProvider } from "@mui/styles";
import { StyledEngineProvider } from "@mui/material/styles";

const customHistory = createBrowserHistory();

const theme = createTheme({
  palette: {
    primary: {
      main: "#242526"
    },
    secondary: {
      main: "#d975d0"
    },
    text: {
      primary: "#E4E6EB",
      secondary: "#B0B3B8"
    },
    background: {
      default: "#242526",
      paper: "#242526"
    }
  }
});

ReactDOM.render(
  <React.StrictMode>
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Router history={customHistory}>
        <ThemeProvider theme={theme}>
          <StyledEngineProvider injectFirst>
            <AppbarTop />
          </StyledEngineProvider>
        </ThemeProvider>
      </Router>
    </LocalizationProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Here is a snippet from my appbar.tsx file:

import React from "react";
import {
  AppBar,
  Box,
  Button,
  Container,
  Menu,
  MenuItem,
  Toolbar
} from "@mui/material";
import HomeIcon from "@mui/icons-material/Home";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles((theme?: any) => ({
  appBar: {
    background: theme.palette.primary.main,
    height: "60px",
    position: "relative"
  }
}));

const AppbarTop: React.FC<{ [key: string]: any }> = () => {
  const classes = useStyles();

  // other functions

  return (
    <>
      <AppBar position="static" className={classes.appBar}>
        <Toolbar>
          <Button
            id="basic-button"
            aria-controls="basic-menu"
            aria-haspopup="true"
            aria-expanded={open ? "true" : undefined}
            onClick={handleClick}
          >
            Dashboard
          </Button>
          <Menu
            // menu items
          >
            <MenuItem>
              <HomeIcon />{" "}
            </MenuItem>
          </Menu>

          // additional components

          <Container maxWidth="sm"></Container>
          <Box></Box>
        </Toolbar>
      </AppBar>
    </>
  );
};

export default AppbarTop;

I'm seeking assistance to understand what could be causing this issue.

Answer №1

Modify this line:

import { ThemeProvider } from "@mui/styles";

To:

import { ThemeProvider } from "@mui/material/styles";

Explanation: There are 2 occurrences of ThemeProvider in this code snippet

  • The first one from @mui/styles: This ThemeProvider sends the Theme object down via context, and it functions properly. You can still access it using the useTheme hook:
const theme = useTheme();

return <Box sx={{ width: 10, height: 10, bgcolor: theme.palette.primary.main }} />
  • The second one from @mui/material/styles: This particular ThemeProvider acts as a wrapper for the previous one but also injects the theme into the
    StyledEngineThemeContext.Provider
    . This allows you to access the theme when utilizing MUI API (such as the sx prop or styled() method). The issue arises because components like Button and Menu utilize the styled() API internally, necessitating the ThemeProvider to be imported from @mui/material/styles for proper functioning.
return <Box sx={{ width: 10, height: 10, bgcolor: 'primary.main' }} />

Further Reading

  • Distinguishing between @mui/material/styles and @mui/styles
  • Troubleshooting palette colors with MUI theme
  • Resolving issues with MUI - makeStyles - Cannot read properties of undefined
  • Implementing Dark Mode with Material UI

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

When working with async functions in JavaScript using await, the second function may not necessarily wait for the first function to complete before executing again

My goal is to implement async await in Angular 10 for loading a list of users from the backend database (built with Spring Boot and MariaDB) using an http request, and then filtering that list for one specific user. However, I'm facing an issue where ...

Attaching onClick event handlers to individual Components within a .map() function for handling multiple selections

I am working on a project where I have implemented multiple divisions and buttons using the .map function. While I have successfully obtained the selected ID of the buttons, my current challenge is to target specific buttons within each division. To ach ...

Why am I unable to set an initial value in useState?

The variable tiles is an array of objects. var originalTiles = tiles; const [newTiles, setNewTiles] = useState(originalTiles); When I log newTiles to the console, I see undefined. What could be the reason for this? ...

Leverage the power of regular expressions in JavaScript for organizing and handling source files

Embarking on my coding journey with JavaScript, I have also been exploring the world of Three.js, a webgl library. After watching tutorials and conducting experiments, I am proud to share my latest creation: . In my code, you'll notice that the obje ...

Provider $uibModalProvider is not recognized as it is linked to $uibModal which in turn is associated with the modalPopDirective

I am currently using Angular's $uibModal in an attempt to create a popup when the page loads, but unfortunately it is not functioning as expected. I suspect there may be an issue with the directive. Here is the code snippet in question: angular.modul ...

Bootstrap 4: Concealed and Revealed Columns?

Is anyone else experiencing an issue where xs is hidden in xs views? I have a hunch it might be due to changes in Bootstrap v4, but I'm curious if there's a way to still make it work without delving into the CSS. My current setup uses the default ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Is there a way to execute a function immediately after an element has completed rendering?

I am facing a challenge where I need to dynamically set the height of one element based on the height of another element. Initially, when the target element finishes rendering, it's 490px tall. However, when I try to retrieve the height of the other ...

Establishing a client cookie will help deter any attempts at re-registering

Due to the inability to run server-side code, I am limited in implementing a PHP session for a registration form. Instead, I have opted to utilize a client cookie to ensure that each person can only register once with a unique email address. After reading ...

Clickable tab for retrieving PDF document through Next.js

I'm attempting to create a button that, when clicked, will download a file. I am currently working on Next.js <a href={cv} download="name cv.pdf"> Download CV </a> This code works correctly in React, but when implemented in Next ...

Masking Aadhaar numbers

I need to find a way to detect when the back button is pressed on an input field. The methods I have tried, e.key and e.which, are returning as undefined in mobile Chrome. How can I make this work? It's functioning properly on desktop. jQuery(funct ...

Steps to show an input button and exit the current window

I am looking for guidance on how to enable or display an input on a webpage if an ajax call is successful. I want this input, when clicked, to be able to close the current window using JavaScript. What would be the most efficient way to accomplish this? B ...

Having trouble with jQuery's recursive animation functionality

I have developed a function to scroll multiple images horizontally in the header of my website. Inside my header, I have implemented code that looks like this: <div class='images'> <!-- this div is 150% wide with overflow hidden --> ...

How should one properly assign an element type provided as an argument?

I'm attempting to define a type for an element passed as a parameter using React.ComponentType. import * as React from "react" type BaseType = { element: React.ComponentType } const Base = ({element: Element}: BaseType) => ( <Ele ...

I would like to know how to create a dropdown menu that shows the country name, flag, and code based on the

I have successfully generated the telephone input field. One requirement is to display the Country flag along with the country name as soon as the dropdown is selected. Another requirement is that once the country is selected, it should display the countr ...

Utilizing jQuery Deferred or Promise to synchronize the completion of multiple asynchronous $.post requests

I'm attempting to make three separate jQuery posts, storing their results in variables that are accessible outside of their scope. Once all three posts have returned successfully, I want to execute another function. Currently, I am using nested callba ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Can you explain the distinction between place-items and align-items?

Wondering about the distinction between using display: flex; align-items: center; versus display: flex; place-items: center; Although they look similar visually, it's worth noting that place-items has 90% browser support while align-items has 92%. ...

Step-by-step guide on how to display a single button within the 'Component' section in React

I recently created a button within a .ts file located in the 'components' folder using the React framework. I am curious to know the fastest method to preview this button that I have designed. Since I am still learning, it wouldn't be feasi ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...