import new font family and override @mui/material font family components

Viewed 664

I would like to import a new font family in a fonts folder and override the mui base font family.

import { responsiveFontSizes, createTheme } from '@mui/material';

import NEWFONTFAMILLY from '../fonts/something.otf'

const theme = responsiveFontSizes(
    createTheme({
        components: {
            MuiCssBaseline: {
                styleOverrides: {
                    fontFamily: [NEWFONTFAMILLY],
                },
            },
        },
    })
);

export default theme;

If I use these code the mui font famiy is applied and not mine :

@font-face {
    font-family: 'NEWFONTFAMILLY';
    src: url(../fonts/something.otf) format('opentype');
}

* {
    font-family: 'NEWFONTFAMILLY';
}

Can someone plese help me ?

I am using @mui/material v5+

1 Answers

I have achieved that following the example that is presented in MUI documentation:

I'd suggest using WOFF2 or WOFF files, not sure if it works with OTF.

// first import your font file
import RalewayWoff2 from './fonts/Raleway-Regular.woff2';

const theme = createTheme({
  // override the theme fontFamily
  typography: {
    fontFamily: 'Raleway, Arial',
  },
  components: {
    MuiCssBaseline: {
     // add font-face to MuiCssBaseline component
      styleOverrides: `
        @font-face {
          font-family: 'Raleway';
          font-style: normal;
          font-display: swap;
          font-weight: 400;
          src: local('Raleway'), local('Raleway-Regular'), url(${RalewayWoff2}) format('woff2');
          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;
        }
      `,
    },
  },
});

Then when you want to add the Component wrapped in the theme you are using like this:

return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <Box
      sx={{
        fontFamily: 'Raleway',
      }}
    >
      Raleway
    </Box>
  </ThemeProvider>
);
Related