Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes.

Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme.

Theme setup:

import { createTheme } from "@mui/material/styles";
import VCRMonoWoff2 from './fonts/VcrMono.woff2';
import VCRMonoWoff from './fonts/VcrMono.woff';

const theme = createTheme({
    typography: {
      fontFamily: 'VCRMono',
    },
    components: {
      MuiCssBaseline: {
        styleOverrides: `
          @font-face {
            font-family: 'VCRMono';
            font-weight: normal;
            font-style: normal;
            src: url(${VCRMonoWoff2}) format('woff2'), url(${VCRMonoWoff}) format('woff');
            unicodeRange: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF;
          }
        `,
      },
    },
  });
export default theme;

Implementation:

import { ThemeProvider } from 'react-bootstrap';
import { CssBaseline } from '@mui/material';
import Box from '@mui/material/Box';

import theme from './theme';

export default function Example() {
    return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <Box>Example3</Box>
  </ThemeProvider>
);
}

Despite implementing this code, the new font doesn't reflect in my theme's typography. However, when using the following snippet, the font changes to VCRMono:

export default function Example() {
    return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <Box sx={{
        fontFamily: 'VCRMono',
      }}>Example3</Box>
  </ThemeProvider>
);
}

Unfortunately, this approach doesn't fulfill my objective of globally overriding the default font.

The MUI Self Hosted Fonts Documentation suggests: "you need to change the theme to use this new font. In order to globally define as a font face, the CssBaseline component can be used." Despite attempting to follow these instructions, I was unable to achieve the desired result.

Any assistance would be greatly appreciated. Thank you.

Answer №1

The previous code was accurate, but the root element needed to be enclosed within the ThemeProvider class.

Here is the corrected version:

  <React.StrictMode>
    <ThemeProvider theme={theme}><Example/></ThemeProvider>
  </React.StrictMode>

By wrapping the ThemeProvider around the root, you ensure that it is applied globally. This information can be found in the documentation on theming.

I overlooked this detail earlier because it is located separately from typography.

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

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

How to retrieve an array stored within a JSON object

I am trying to access a specific array within an object from a JSON file. Here is the snippet of the data I'm dealing with: best-sellers": [ { "title": "Chuteira Nike HyperVenomX Proximo II Society", "price": 499.90, "installmen ...

Determining when to include @types/packagename in React Native's dev dependencies for a specific package

Just getting started with React Native using typescript. Take the package vector icon for example, we need to include 2 dependencies: 1. "react-native-vector-icons": "^7.1.0" (as a dependency) 2. "@types/react-native-vector-icons": "^6.4.6" (as a dev ...

Using Reactjs: How do you insert HTML code into the primaryText of a list item?

Is it possible to include a span element inside a ListItem like so: <ListItem primaryText={"<span class='inner'>Some important info</span>" + item.title} /> When I view the rendered content, the output is not an HTML span ...

Difficulty persisting when removing accents/diacritics from a string in Angular with IE 11

When attempting to utilize the String.normalize("NFD").replace(/[\u0300-\u036f]/g, "") method, I encountered an issue in IE11. ERROR TypeError: The object does not support the property or method "normalize" ...

Utilize a viewpoint alteration alongside a floating effect on a specific element

I thought this would be an easy task, but I seem to be missing something as it doesn't work for me. The goal is to use the perspective() and rotateY() functions in a transform to create a perspective effect on an element. Additionally, there should b ...

Modify the appearance of children in MaterialUI within a single specific component

Utilizing the <ListItemIcon/> component from Material-UI, I am faced with a scenario where I need to display two different Icons in one component. These icons should have varying sizes and styles. The <ListItemIcon/> is constructed using an SVG ...

What is the best way to set the first option in a mat-select to be

My approach to date selection involves using 3 mat-select components for day, month, and year. You can view a demo of this setup here. In an attempt to improve the code, I decided to set the initial options as null by modifying the following lines: allDat ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Handling events for components that receive props from various components in a list

In my code, I have a component called PrivateReview which includes event handlers for updating its content. export default function PrivateReview(props) { const classes = useStyles(); const removeReviewAndReload = async () => { await ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

displaying post data in the URL address bar

During the development of my portal using angular 5, everything was running smoothly in the testing environment. However, due to production requirements, I made some changes to access modifiers from private to public. This modification has caused issues in ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

Unlock the full potential of MaterialUI with Optional PaletteIntention members. Discover new ways to customize

In my search through the Material-UI documentation, I have been unable to locate information on how the properties "light", "dark", and "contrastText" of a PaletteIntention are utilized or their intended purpose. While I understand that I can directly ac ...

An error was encountered in the rxjs-compat module at operator/shareReplay.d.ts line 2, character 10: TypeScript error TS2305

Currently, I am in the process of upgrading a basic Angular skeleton application from version 5 to version 6. However, I have encountered an issue while attempting to run the application: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Can the detectChanges() method in Angular cause any issues when used with the form control's valueChanges event?

Within my parent Component, I am working with a formGroup and updating its value using patchValue method. ngAfterViewInit() { this.sampleform.controls['a'].patchValue ...} I then pass this form to a child component in the parent component's ...

Make the header component of @mui/material/Table stick to the top

Trying to implement a sticky header for a Material Table component but encountering issues with it not working properly. Attempted to set the rows in the header as sticky so that when scrolling, the header remains fixed in place. Here is the code snippet: ...