What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the issue persists.

Below is my index.tsx:

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { Provider } from "react-redux";
import configureStore from "./redux/stores/main";
import * as serviceWorker from "./serviceWorker";
import { createMuiTheme } from "@material-ui/core";
import myTheme from "./styling/mainTheme";
import { ThemeProvider } from "@material-ui/styles";

const theme = createMuiTheme({
  typography: {
    fontFamily: ["Arial"].join(",")
  }
});

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <Provider store={configureStore()}>
      <App />
    </Provider>
  </ThemeProvider>,
  document.getElementById("root")
);

serviceWorker.unregister();

This is my app component:

import React from "react";
import { useSelector } from "react-redux";
import HeaderContainer from "../containers/layout/header/HeaderContainer";
import { ThemeProvider, useTheme } from "@material-ui/styles";
import theme from "../styling/mainTheme";
import { createMuiTheme } from "@material-ui/core";



const App: React.FC = () => {
    const theme = useTheme();
  return (
      <div className="App">
          <HeaderContainer />
      </div>
  );
};

export default App;

Here's the header container (containing logic):

  import * as React from 'react';
import Header from '../../../components/layout/header/Header';

export interface HeaderContainerProps {
}

export default class HeaderContainer extends React.Component<HeaderContainerProps> {
  public render() {
    return <Header />
  }
}

Lastly, here is the header component:

import * as React from "react";
import { styled } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";



export default function Header() {
    return (
        <AppBar>
            <h2>Hello</h2>
        </AppBar>
    )
}

I have attempted various placements of the ThemeProvider with no success in changing the font to Arial for my h2 tag. Any insights on resolving this issue would be greatly appreciated. Thank you!

Answer №1

After reviewing the documentation for material-ui, it appears that you have mistakenly imported some elements from the library in an incorrect manner. As the documentation suggests -

import { useTheme } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

This can actually be simplified to

import { useTheme, createMuiTheme } from '@material-ui/core/styles';

The same concept applies to ThemeProvider as well

import { ThemeProvider } from '@material-ui/core/styles';

Answer №2

When working with MUI V5, it is important to note that you now need to import ThemeProvider and createTheme from @mui/material/styles instead of @mui/styles.

import * as React from 'react';
import ReactDOM from 'react-dom';
import {red} from '@mui/material/colors';
import { ThemeProvider, createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: red[500],
    },
  },
});

function App() {
  return <ThemeProvider theme={theme}>...</ThemeProvider>;
}

ReactDOM.render(<App />, document.querySelector('#app'));

source

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

changing tooltip color in bootstrap based on the parent element

Is there a way to adjust the bootstrap tooltip background-color based on the container? For example, my header has a white background and my footer is black. #header .tooltip-inner{ background-color:fade(@grayWhite,80); } #footer .tooltip-inner{ backgro ...

Issues with jQuery toggle functionality have been reported specifically on the iPhone8 and other iOS devices

Hi everyone, I'm facing an issue with the header on my website. It displays a hamburger menu on small screens, and while it works perfectly on PCs and Android phones, it's unresponsive on iOS, specifically on my iPhone 8. I've tried using va ...

Utilizing media queries for responsive design in CSS

I've been working on aligning the page content for different browser sizes using CSS. However, I'm having an issue with the first @media statement - no matter what changes I make in there, it doesn't affect the layout. I've been using ...

Having trouble toggling webcam video in React/NextJS using useRef?

I have created a Webcam component to be used in multiple areas of my codebase, but it only displays on load. I am trying to implement a toggle feature to turn it on and off, however, I am facing difficulties making it work. Below is the TypeScript impleme ...

Unable to see the changes made to the Understrap child-theme and the color variable in Sass is not

I am trying to adjust the main theme color assigned by $primary in _theme_variables.scss. I changed the default value from $purple to $orange while using npm run watch-bs (browser-sync). However, the change is not reflecting on the home page: https://i.ss ...

Tips for creating floating and right-aligned notifications using CSS in Vue.js

Struggling to position my basic notification component in the top right corner. Here is my HTML: <div class="notifications"> <p>{{ notification.message }}</p> </div> This is my notifications class: .notifications { position: ...

Error message encountered: React hydrate TypeError - the function __webpack_require_.i(...) is not recognized as a

I encountered a webpack TypeError while attempting to use hydrate() in my index.js file. Strangely, the error does not appear when I use ReactDOM.render() instead of hydrate. My intention behind using hydrate was for server-side rendering. src/index.js i ...

The ReactJS form fails to show any updates upon submission

Here is the code snippet I have been working on: const [messages, setMessages] = useState(messagesList); const [addMessage, setAddMessage] = useState({ messageSent: '', }); const addMessageChange = (event) => { event.preventD ...

What are the best practices for properly deploying a React Vite project in production mode?

Currently, I am utilizing Vite alongside React and my aim is to deploy the project in production mode on a server. Below is the content of my vite.config.js file: export default defineConfig({ esbuild: { loader: "jsx", }, optimizeDeps: ...

Modifying Navbar on the fly in React for logged-in users: A guide

My App component includes a navbar (component navbarUser). I want to dynamically change the navbar to display logout and profile options when the user is logged in. Currently, the navbar does not update when the user logs in. I have utilized an useEffect ...

"Enhance Your Slide Up/Down Menu with a Unique Hover Effect in jQuery

HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="navigation_desktop"> <div class="button_desktop_01">1.0 Main Menu <div class="SlideItem ...

VS code showing live server as installed but failing to function properly

After installing the live server extension, I noticed that my browser is not updating when I save my HTML or other files. What could be causing this issue? ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

Having trouble with the base64 output in React image cropping?

I am having some difficulties cropping and uploading an image to the server. The API server requires the image in base64 format, but I am receiving it as a blob. Does anyone know of a workaround for this issue? Any help would be greatly appreciated! I&apos ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

"Text data will be automatically cut at the end of a page and continue

I encountered the following issue As depicted in the image The data is not being displayed properly In the next td, the last character 3 is also printed on the next line Is it possible to avoid page footer and header without adjusting the page margin? ...

Creating a row of aligned card components in React

Recently, I began learning React and successfully created a card component using Material UI. However, this time around, I'm attempting to create it using axios and map() methods. I expected the cards to be displayed in the same row horizontally, not ...

Tips for using nested flexbox with images

I am facing a straightforward use case where I have an image and a div containing text. The current setting for the div is flex column. My goal is to change the flex setting to row so that the text and image appear side by side. Despite having the corre ...