In my React web application, I tried to implement a custom font by writing the following 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
Despite my efforts, the custom font did not work as expected. As a workaround, I attempted to customize the font using plain CSS.
I came up with a solution by eliminating the overrides
property in createMuiTheme
and utilizing this CSS code:
<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>
Although this is a makeshift solution, I am seeking a more effective approach tailored for a project incorporating Material UI. Could there be an error in how I implemented createMuiTheme
?