How to add a custom font in React Material UI

Last updated on Oct 15, 2022 by Suraj Sharma



In this tutorial, you will learn how you can add a custom font and override React material ui font.

FYI, React Material UI is built on top of Roboto Font.

However, React Material UI provides a way to override the font with our own custom font.


Let's get started


Open the theme.js file or if you haven't created a theme.js file yet, create one in the src folder.

Download a font of your choice, for this tutorial we are going to use Titillium Web, download the font from Google fonts.


Create a folder Fonts in the src folder, move the downloaded font to the Fonts folder.


add custom font in material ui


Now paste the following code in your theme.js file


import TitilliumWeb from './Fonts/TitilliumWeb-SemiBold.ttf';
 
const titilliumWeb = {
 fontFamily: 'TitilliumWeb',
 fontStyle: 'semi-bold',
 fontDisplay: 'swap',
 fontWeight: '600',
 src: `
   local('TitillumWeb'),
   local('TitillumWeb-SemiBold'),
   url(${TitilliumWeb}) format('ttf')
 `,
 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',
};

Create a variable theme if you don't have it in your theme.js file.


import { createTheme } from '@mui/material/styles';

const theme = createTheme({
 
})

export default theme;

Paste the following code to append Titillium Web to the typography fontFamily


const theme = createTheme({
 typography: {
   fontFamily: ['"Open Sans"', 'TitilliumWeb', 'Roboto'].join(','),
  }
})

Now, We are going to override the material ui CssBaseline component to include a global css style.

Update your theme variable with the following code:


const theme = createTheme({
  typography: {
    fontFamily: ['"Open Sans"', 'TitilliumWeb', 'Roboto'].join(','),
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [titilliumWeb],
      },
    }
  }
})


If you want to style a particular element with the custom font, then you can override the fontFamily of the element


const theme = createTheme({
  typography: {
    fontFamily: ['"Open Sans"', 'TitilliumWeb', 'Roboto'].join(','),
    h1: {
     fontFamily: '"TitilliumWeb", Open Sans',
    }
  }
})


Inside your index.js, paste the following the code.


import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider } from '@mui/material/styles';

import App from './App';
import theme from './theme';

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <CssBaseline />
    <App />
  </ThemeProvider>,
  document.getElementById('root')
);


Congrats! You have successfully added the custom font to your React Material UI project. 😊



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.