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

Utilizing useContext data in conjunction with properties

When using useContext in a component page, I am able to successfully retrieve data through useContext within a property. customColorContext.js import { createContext, useEffect, useState, useContext } from 'react'; // creating the context objec ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

The RSuite Cascader search field is malfunctioning and not responding to input

I have integrated several RSuite components into a mat-ui app and everything seems to be functioning well. However, I am facing an issue with the Cascader component, which is crucial for my project. Despite fixing the popup display issue by adjusting the z ...

Update button Image upon click

Is there a way to swap the image on a button when it's clicked? I want my button to start with one icon, but then change to another icon once it has been clicked. How can I achieve this effect? Any suggestions on how to make this happen? Check out ...

What are the best practices for styling a component in Fluent UI when using React and TypeScript?

I'm attempting to set a background color for this specific div element: import * as React from 'react' import { Itest } from '../../../../../models' import { getPreviewStyles } from './preview.style.ts' type IPreviewP ...

Leveraging the withWidth higher order component (HOC) provided by

I am currently using version 3.9.2 of Material UI and experimenting with the withWidth HOC in a server-side rendered application. When I disable Javascript in the debugger options of Chrome Developer Tools, everything functions as expected by displaying t ...

Testing the mirkoORM entities at a unit level

Trying to perform a unit test on a method within a MikroORM entity, I am attempting to populate a mikroORM collection field with test data. Specifically, I am using jest for this task: describe('Team Tests', () => { it('isLeader shoul ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

Utilize the get method to showcase data in a material UI table for a React application

Just starting out with React. Managed to create a table component with hard-coded data. However, I now have all the data stored in table.json. Can someone guide me on how to fetch values from table.json using an axios get request an ...

Having trouble displaying Font Icons with MUI v5?

Seeking help with incorporating Material UI v5's Icon class into my project. I inserted the below code in my index.html file: <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> After tha ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

How can I stop MUI Button from automatically becoming fullWidth?

One of the challenges I encountered was styling a Button component from MUI: export const ButtonStyle = styled((props) => <Button {...props} />)(({ theme }) => ({ marginTop: 8, marginBottom: 8, width: 'auto', borderRad ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Second AppBar with Material UI sticks below the first AppBar

Is there a way to make an AppBar sticky below another AppBar instead of overlaying it when using the position "sticky"? I'm thinking I might need to set something like top: "myTopAppBar px", but I'm not sure how to do that. Any suggestions? Chec ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Error: Unable to retrieve the "button" property because theme.typography is not defined

I'm in the process of setting up a new React application with Material-UI (MUI). To customize our styles and containers, we have decided to use styled-components. Following the documentation, I am configuring MUI with styled-components. Additionally, ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...