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

There is no 'Access-Control-Allow-Origin' header found on the requested resource while utilizing AWS API Gateway in conjunction with AWS Lambda

Working on my backend, I have integrated AWS API gateway with AWS Lambda. I made sure to enable cors for my endpoint. However, upon testing the endpoint on the browser, I encountered the following error: No 'Access-Control-Allow-Origin' header ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

Aligning the stars with CSS

One of the components I have deals with a star rating system, and I thought it would be cool to use Font Awesome icons for half stars. Everything is working well except for the CSS styling aspect. While I managed to position some of the stars correctly by ...

React: Submit button not triggering form submission despite having a valid submit event handler and correct syntax

My question stands out from existing ones as it features valid syntax, correct use of type="submit" on the button, and a simple onSubmit handler on the form. Despite this, clicking the button fails to trigger the onSubmit handler. To illustrate ...

The rounded corners feature of PIE.htc does not seem to be functioning properly on Internet Explorer

Check out my code below: http://jsfiddle.net/parag1111/s5RLb/ Make sure to place PIE.htc in the CSS folder. I've already included the necessary JS and behavior for PIE.htc. Please provide any additional suggestions to ensure compatibility with IE8 a ...

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 ...

The function _this2.setState does not work properly in asynchronous situations within React

I have an onChange handler that triggers a Promise Resolve function. This function fetches data array using "PromiseValue", and I use ".then( result )" to retrieve the array field. It works when I print "result" with console.log. However, the issue arises ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

Excessive white space within a relative block div causing the content to appear smaller in comparison

Currently, I am developing a straightforward form that includes CSS-based help boxes. These help boxes are designed to appear when the user hovers over the corresponding row. After leaving my project untouched for a few days, I encountered some bugs upon ...

Tips for efficiently managing state across your React client components when utilizing a parent server component

Within my next.js application, there exists a specific page containing two distinct components known as X and Y. // page.tsx import X from './X' import Y from './Y' const Page = () => { return ( <div> <X /> ...

Creating a seamless and interactive online platform

I am in the process of designing a website that has a sleek and dynamic layout, rather than just a static homepage. Let me explain further: Here is my current setup so you can understand what I am trying to achieve. By dynamic, I mean that when the page ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Updating the state of an object nested within another object in React JS

So, I have a nested object within another object and I need to update the state of one or more properties in the inner object. This is my current state: const [products, setProducts] = useState({ name: '', type: '', price: '& ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

Issues with rendering Google Maps on google-maps-react persists, stuck endlessly in loading phase

After following the tutorial for google-maps-react, I attempted to display a Google Map in my app using the same structure as the example. However, the map is not rendering. Link to Tutorial There are no errors showing up in my console. Here is the dire ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. <div className="imageGrid__container"> <di ...

CSS text width going from left to right

I am attempting to create a text fade effect from left to right, inspired by the technique discussed in this answer. However, I would like the text to be concealed behind a transparent background div instead of the white background used in the example. I ...

There is an issue with the type candidate in the Notion API, resulting in

In this instance, the troublesome code causing issues is displayed below: import {Client, LogLevel} from "@notionhq/client"; const notion = new Client({ auth: process.env.NOTION_TOKEN, logLevel: process.env.NODE_ENV !== 'product ...