Having trouble adding a custom font with override to MuiCssBaseline in react-admin, the @global @font-face seems

I am attempting to integrate the NotoSansSC-Regular.otf font from Google into my react-admin application as the default font for simplified Chinese text. I have managed to make it work by including the fonts in the root HTML file using CSS, like this:

  typography: {
    fontFamily: ["Roboto", "Helvetica", "Arial", "sans-serif", "notasansregular"].join(","),
  },

However, all the resources I came across suggest that I should also be able to achieve the same result through the following method:

import notasansregular from "../../public/fonts/chinese/NotoSansSC-Regular.otf";
...
const notafont = {
  fontFamily: "notasansregular",
  fontStyle: "normal",
  fontWeight: "normal",
  src: `
    url(${notasansregular}) format('opentype')
  `,
};
...
const myTheme = {
...
  overrides: {
    MuiCssBaseline: {
      "@global": {
        "@font-face": [notafont],
      },
    },
...
}

Despite trying various approaches, including using different URLs and simplifying the font path in the url('NotoSansSC-Regular.otf'), I still cannot get it to work. This is frustrating especially because a few examples I found placed the <CssBaseline /> directly within a ThemeProvider in the JSX code. However, in the case of react-admin, the placement seems to be causing some inconvenience as implementing it inside or outside the <Admin /> component does not yield any results either.

Answer №1

If you're working with Mui version 5, the syntax differs slightly:

const myTheme = createTheme({
  components: { // not overrides!
    MuiCssBaseline: {
      styleOverrides: `
        @font-face {
          font-family: 'Noto Sans SC';
          font-style: normal;
          font-display: swap;
          font-weight: 400;
              src: local('NotoSansSC'), 
                   local('NotoSansSC-Regular.otf'), 
                   url(${notasansregular}) format('otf');
          unicodeRange: // the unicode range for SC
        }
      `,
    },
  },
})

ETA: Demo of Mui version 4

Answer №2

For those using Mui v5 and needing multiple fonts, here is the solution:

import AbradeRegular from 'assets/fonts/Abrade-Regular.ttf'
import AbradeMedium from 'assets/fonts/Abrade-Medium.ttf'
....

const abradeRegular = {
  fontFamily: 'Abrade',
  fontStyle: 'normal',
  fontWeight: 'normal',
  src: `url(${AbradeRegular}) format('truetype')`,
}

const abradeMedium = {
  fontFamily: 'Abrade',
  fontStyle: 'normal',
  fontWeight: 500,
  src: `url(${AbradeMedium}) format('truetype')`,
}
....

theme.components = {
  MuiCssBaseline: {
    styleOverrides: {
      html: [
        {'@font-face': abradeLight},
        {'@font-face': abradeRegular},
        {'@font-face': abradeMedium},
        {'@font-face':abradeSemiBold},
        {'@font-face': abradeBold},
        {'@font-face':abradeExtraBold},
        {'@font-face':abradeBlack}
      ],
      'html, body': {
        padding: 0,
        scrollbarWidth: 'thin',
      },
}}}

Answer №3

Instructions on CSS template syntax in Mui documentation:

Important note: avoid using commas , between @font-face declarations.

import RobotoRegular from '@assets/fonts/roboto-regular.woff2';
import RobotoBold from '@assets/fonts/roboto-bold.woff2';
import RobotoMedium from '@assets/fonts/roboto-medium.woff2';

const customTheme = createTheme({
  typography: {
    fontFamily: [
        'Roboto',
        'sans-serif',
        ].join(','),
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: `
        @font-face {
          font-family: 'Roboto';
          font-style: normal;
          font-display: swap;
          font-weight: 400;
          src: url(${RobotoRegular}) format('woff2');
        }
        @font-face {
          font-family: 'Roboto';
          font-style: normal;
          font-display: swap;
          font-weight: 700;
          src: url(${RobotoBold}) format('woff2');
        }
        @font-face {
          font-family: 'Roboto';
          font-style: normal;
          font-display: swap;
          font-weight: 500;
          src: url(${RobotoMedium}) format('woff2');
        },
      `,
    },
  },
});

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

Why is there a mismatch between CSS and Angular 6 selector components?

website.html <website-chat></website-chat> chat-page.html <h1>Greetings</h1> chat-script.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'website-chat', templateUrl: '. ...

"(PHP)WordPress produces a dynamic menu that adapts to different screen sizes

I recently created a menu on my WordPress site [ and I'm facing an issue with making it display vertically in a responsive way. The code in header.php is as follows: <!-- header --> <header> <div class="overNavPanel"> ...

Exploring the combination of React Hooks (specifically useState) and Mobx without the use of mobx-react

In my React app (built with TypeScript), I am trying to utilize React hooks, specifically useState, to handle the form state and also use it as an observable component for MobX store. However, I am encountering an error message that says, Hooks can only ...

div with fixed position and scrollable content

I'm exploring ways to create a simple webpage layout inspired by the traditional index setup. The idea is to have a fixed header/navbar div that is 200px in height, with a second div below it containing scrollable content that fills the remaining vert ...

Unable to destructure props and assign them to a react-bootstrap component

I recently installed react-bootstrap and I am looking to customize the default buttons in my project. My goal is to simplify the button creation process by just using <Button> without specifying a variant option for most buttons. import * as bs from ...

Shift the position of an <img> downwards by 50% of its height while maintaining the flow of the elements

Consider this snippet of code below <div> <img src="http://www.lorempixel/100/200" /> <p> Bla bla bla bla </p> </div> I am trying to figure out how to move the image 50% of its height and also adjust the ...

Setting focus on the content of a Tooltip component from Material UI is possible when triggering the onKeyPress event, however, it is not possible when triggering the onClick

Utilizing the Tooltip component from MUI within my custom TooltipComponent has been an interesting experience. Much like a Dialog, users can trigger content to appear by clicking on an element (in this case, a div with the text "CLICK"). This popup content ...

Differences in typography across Mozilla Firefox and Internet Explorer

I have come across a question that seems quite common, yet unsolvable. However, I will give it a try anyway. Take a look at this image: To view a larger version of the image, visit the following URL: https://i.stack.imgur.com/dddNm.jpg HTML code: <d ...

Joi npm package is throwing a TypeError because it cannot read the property 'extract' of undefined

Hello! I am encountering an issue while trying to access the username property. The error message I receive is "Type Error: Cannot read property 'extract' of undefined." Below is my current code, where I am utilizing the Joi package: class LoginF ...

In React Material UI, there seems to be an issue where the image and h4 elements are not displaying next

I am currently working with material ui in react. I am facing an issue where the image and h4 elements are aligned vertically instead of being placed adjacent to each other. I have tried adjusting the width, but it doesn't seem to be working. https:/ ...

Is your margin not functioning correctly? Is padding taking on the role of margin?

One issue I'm encountering is that the margin isn't behaving as expected in this example. The padding seems to be working like margin should. Why is that? Print Screen: https://i.stack.imgur.com/N1ojF.png Why is it that the margin in the h3 ta ...

Error: The method onSaveExpenseData in props is not defined as a function

I am currently learning how to pass data from a child component to a parent component in React I encountered an error: TypeError: props.onSaveExpenseData is not a function I would appreciate any help as I am still in the learning phase and this error has ...

Is it possible to customize the Checkbox color within Material-UI's Autocomplete feature?

Having trouble changing the color of the Checkbox component in React using Material-UI's Autocomplete feature. Check out my code snippet: <Checkbox icon={icon} checkedIcon={checkedIcon} style={{ marginRight: 20 }} value={options} name="is ...

Challenges with implementing TailwindCSS classes in a Next.js application

I've encountered some issues in my nextJS app with utilizing certain TailwindCSS classes such as top, left, or drop-shadow. Even after attempting to update Tailwind from version 1.9.5 to 3.3.3, I have not seen any changes. I believe that I am import ...

Is there a way to slow down the falling effect on my navigation bar?

As I was working on my personal website, I had a creative idea to add a falling-down animated effect instead of keeping the layout fixed. Utilizing bootstrap for navigation, I encountered some difficulty in controlling the speed of the falling effect. Any ...

Issue with fixed header in Vuetify v-data-table not functional

While working with the Vuetify v-data-table component, I have enabled the fixed-header property. However, I have noticed that the table header is scrolling along with the table body. I am using the latest version of Chrome. Does anyone know how to addres ...

Ways to modify the font style of Python comments in JupyterLab's code cells and code editor:

Many resources discuss how to change font families for all content, but I am seeking guidance on making syntax-specific changes. For example, I would like to switch the font style of Python comments from italic to normal. Can anyone offer assistance? Thank ...

Aggregate the chosen elements into a single entity

I've got a component named "itemSelection" and another one called "Item" Within the itemSelection component, I simply map through an API response like this: <div className="row"> {this.state.items.map(i => <Item name={i.name} quantit ...

Items on Bootstrap have been expanded to fit larger screens

I'm currently working on a webpage () and facing an issue with the size of objects on a specific screen resolution. When users click on items in the accordions, multiple information cards are displayed. However, on larger screens, these cards appear ...

Difficulty in using window.scrollTo within useEffect in reactJS

I'm facing an issue where I am trying to use window.scrollTo on the initial render using the useEffect function. I have stored the vertical offset as an integer in localStorage, but the scrolling is not working and remains at position 0. Problem with ...