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

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

What could be the reason for only one of my states being modified when I call my function?

Currently, I have a single state in React.js consisting of two key-value pairs for length validation and character validation: const [validation, setValidationState] = useState({ lengthValidation: "", characterValidation: "", }); These states are e ...

How to resolve the issue of a sticky header not functioning properly with a resizable column in Primeng

Currently, I am facing an issue while trying to incorporate both column resize functionality and sticky header in my table. Interestingly, the sticky header feature works perfectly fine when used alone without the column resize. However, when I attempt to ...

Exploring the features of material-ui's GridList

Excuse me if this question seems silly, but I've only just started learning React a few days ago. For my current project, I need to implement a 'Like' system using material-ui's GridList. There will be eight pictures where users can cl ...

Exploring Material-UI v1: Harnessing the power of custom colors in theme customization

As a newcomer to material-ui, I'm facing a seemingly simple issue. I am currently working with material-ui v1 and attempting to modify the primary color of the theme. Below is my existing theme object structure without any custom colors: import { cre ...

Troubleshooting Problems with Cookie and Session Management

I'm encountering an issue while trying to set cookies and session values during login on the backend, which is built in node js. However, when react calls the API to verify these cookies or session values, they are returning as undefined... My middle ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

Unusual red border appearing on React JS MUI Datepicker

Within my reactJS application, I have successfully implemented a datepicker with no issues. However, on a custom page, I have noticed a peculiar red border surrounding another datepicker: https://i.stack.imgur.com/DXYj7.png The code in question is as fo ...

The CSS background shadow on one div behaves differently compared to the neighboring div

Currently, I am facing an issue where I have two divs positioned next to each other in a line. http://jsfiddle.net/A5Jc7/60/ The HTML structure is as follows: <div> <div class="box1"></div> <div class="box2"></div> ...

Is it possible for a MUI control to automatically close itself when clicked outside of the component?

Currently diving into the world of MUI 5 component design. Does anyone know where I can locate the code responsible for closing a component when clicking outside of it? I've searched through the source code but couldn't pinpoint it. This functi ...

"Exploring the process of incorporating externals similar to webpack in the latest version of Next.js, specifically

When working with webpack, I discovered a way to use "externals" in order to load additional components or modules into applications and import them. In this example, the component "ymaps3" is loaded as an external script without a react wrapper. Below is ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Updating ListItemText styles in MUI when active with react-router

I am currently using ListItem from Material-UI. I am attempting to increase its font weight when it is active, but for some reason the font-weight property does not seem to have any effect. Below you will find the code snippet: <List component=&a ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

Issue: The key prop is missing for an element within an array in React

While attempting to build my next.js application, I keep encountering an issue that reads: Error: Missing "key" prop for element in array react/jsx-key within each component. https://i.stack.imgur.com/BIW ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Exploring the incorporation of Next JS IMAGE into Material UI card media

In my current project, I am utilizing both Next JS and Material UI. When it comes to optimizing images, I am leaning towards using the Next JS Image component for efficiency. At the moment, my card media section is structured as follows. Through an API ca ...

Leverage React Final Form to dynamically adjust conditions based on the values within the form

To dynamically generate a specific number of fields based on user input from the initial form step, I am utilizing a multi-step form with a "Wizard" class as the <Condition /> component does not fit my requirements. Essentially, I need to retrieve v ...

Methods for dynamically altering the background color of a parent component from a child component

Currently, I am working on a T-shirt design application using fabric.js within reactjs. I have encountered an issue when attempting to change the color of the t-shirt. My goal is to allow the color of the T-shirt to be changed from the child component but ...