Skip to content

Custom font isn't loading on custom theme for Material UI #18901

@macabeus

Description

@macabeus

Current Behavior 😯

I'm using a custom font in my React web application. So I wrote this code:

import React, { FunctionComponent } from 'react'
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'
import SofiaProLightTtf from '../../assets/font/sofia-pro-light.ttf'
import SofiaProTtf from '../../assets/font/sofia-pro-regular.ttf'

const sofiaPro = {
  fontFamily: 'Sofia Pro',
  fontStyle: 'normal',
  fontWeight: 100,
  src: `url(${SofiaProTtf})`
}

const sofiaProLight = {
  fontFamily: 'Sofia Pro Light',
  fontStyle: 'normal',
  fontWeight: 100,
  src: `url(${SofiaProLightTtf})`
}

const theme = createMuiTheme({
  typography: {
    fontFamily: 'Sofia Pro',
    body1: {
      fontFamily: 'Sofia Pro Light'
    }
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [sofiaPro, sofiaProLight]
      }
    }
  }
})

const Theme: FunctionComponent = ({ children }) => (
  <MuiThemeProvider theme={theme}>{ children }</MuiThemeProvider>
)

export default Theme

But it isn't working. So I tried to customize the font using plain CSS.

I found a workaround removing the overrides property in createMuiTheme and with this CSS:

<style>
  @font-face {
    font-family: 'Sofia Pro';
    font-style: normal;
    font-weight: 100;
    src: url("/65e0f064b96a52b92f7293b673054b0b.ttf");
  }

  @font-face {
    font-family: 'Sofia Pro Light';
    font-style: normal;
    font-weight: 100;
    src: url("/d15399628129cc8121c08073df25f0dd.ttf");
  }
</style>

But it is a very bad workaround...
I opened a question on Stack Overflow but nobody answered, so I think that it's a bug.

I'm using the latest Material UI version:

"@material-ui/core": "4.7.0",
"@material-ui/lab": "4.0.0-alpha.34",

Expected Behavior 🤔

We need be able to load a custom font using only createMuiTheme, without any custom CSS.

Steps to Reproduce 🕹

  1. Create a new project. You'll need to add this rule on your webpack.config.js:
  {
    test: /\.ttf$/,
    use: 'file-loader',
    exclude: /node_modules/,
  },
  1. Add some custom fonts on your project, and copy and paste the first code block on this issue

  2. On your index.tsx, use:

import React from 'react'
import ReactDOM from 'react-dom'
import Theme from './theme'

const App = () => (
  <Theme>
    <p>hello world</p>
  </Theme>
)

ReactDOM.render(<App />, document.getElementById('app'))
  1. The custom font wasn't load.

Context 🔦

I need to use a custom font. Beside I found a workaround, I would like to have a better code.

Your Environment 🌎

Tech Version
Material-UI v4.7.0
React 16.12.0
Browser Chore, Firefox and Safari
TypeScript 3.7.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions