Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import and use a custom font in a material-ui theme?

I'm trying to import and use the Yellowtail font (from Google Fonts) in my React app in a Material-UI theme.

As far as i know all google fonts are on npm, I've installed it, with the

npm install typeface-yellowtail --save

command.

I have imported it in App.js, put it in the font-family part of the theme, passed the theme to the MuiThemeProvider, but it does not work. What did I miss?

This is what i have inside of App.js (header contains an AppBar with some grids and body contains only an h1 text for testing)

import React, { Component, Fragment } from 'react';
import Header from './Components/Layouts/Header';
import AppBody from './Components/Layouts/AppBody';
import Footer from './Components/Layouts/Footer'; 
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core';
import 'typeface-yellowtail';

const theme = createMuiTheme({  
  typography: {
    fontFamily: 
      '"Yellowtail", cursive',
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <Header />
        <AppBody />
        <Footer />       
      </MuiThemeProvider>
    );
  }
}

export default App;
like image 967
boglarkaszell Avatar asked Sep 28 '19 11:09

boglarkaszell


People also ask

How do I add a font to material UI theme?

Method 1: Use Google Fonts CDN To be able to use the fonts, you'll have to initialize it using the CreateMuiTheme which is an API provided by Material UI that generates a custom theme based on the options received and ThemeProvider which is a component used to inject custom themes into your application.

How do I import fonts into MUI?

To self-host fonts, download the font files in ttf , woff , and/or woff2 formats and import them into your code. ⚠️ This requires that you have a plugin or loader in your build process that can handle loading ttf , woff , and woff2 files. Fonts will not be embedded within your bundle.

How do I change the font in React material UI?

To change the font family of all React Material UI components, we can call the createTheme function provided by Material UI to set the font styles for the theme. Then we apply the theme with ThemeProvider to apply the styles to the whole app. We call createTheme with an object that has the typography.


5 Answers

Instead of installing via npm, you can just first load CSS file.

@import url('https://fonts.googleapis.com/css?family=Yellowtail&display=swap');

Import this CSS file

import './assets/css/yellowtail.css';

Now you don't need to use any @font-face. This can be used with font families like normal.

like image 110
Nautatava Navlakha Avatar answered Oct 18 '22 02:10

Nautatava Navlakha


You are missing three things:

  • Import the npm package as something
  • Use the CssBaseline component
  • Add an override to the object provided to createMuiTheme()

See example:

import React, { Component, Fragment } from 'react';
import Header from './Components/Layouts/Header';
import AppBody from './Components/Layouts/AppBody';
import Footer from './Components/Layouts/Footer'; 
import { MuiThemeProvider, createMuiTheme, CssBaseline } from '@material-ui/core';
import yellowtail from 'typeface-yellowtail';

const theme = createMuiTheme({  
  typography: {
    fontFamily: 
      '"Yellowtail", cursive',
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [yellowtail],
      },
    },
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        <Header />
        <AppBody />
        <Footer />       
      </MuiThemeProvider>
    );
  }
}

export default App;

Example CodeSandbox (MUI v3): https://codesandbox.io/s/late-pond-gqql4?file=/index.js

Example CodeSandbox (MUI v4): https://codesandbox.io/s/pensive-monad-eqwlx?file=/index.js

Notes

  • MuiThemeProvider changed to ThemeProvider in the transition from Material-UI v3 to v4. If you are on v4, this is the only change needed - this example code otherwise works on both versions.

  • You must wrap text in Material-UI's Typography component for the font to be used.

like image 31
psychedelicious Avatar answered Oct 18 '22 01:10

psychedelicious


There is a much easier way of doing this that doesn't require a .css file or installing any extra packages.

If your font is available over a CDN like Google Fonts then just imported into the root HTML file of your app:

<link
  href="https://fonts.googleapis.com/css2?family=Yellowtail&display=swap"
  rel="stylesheet"
/>

Then add one line in the Material-UI theme:

const theme = createTheme({
  typography: { fontFamily: ["Yellowtail", "cursive"].join(",") }
});

Working codesandbox example with Material-UI v5.

like image 40
benmneb Avatar answered Oct 18 '22 03:10

benmneb


Update: Since @ekkis mentioned I'm adding further details on how to include the Google Font. The following answer assumes you're using Material UI v4.10.1

  1. Install the gatsby-plugin-web-font-loader to install Google font.

  2. Edit gatsby-config.js to include the plugin and the Google font.

module.exports = {
  plugins:      [
    {
      resolve: "gatsby-plugin-web-font-loader",
      options: {
        google: {
          families: ["Domine", "Work Sans", "Happy Monkey", "Merriweather", "Open Sans", "Lato", "Montserrat"]
        }
      }
    },
  ]
}
  1. To use the font, create a file called theme.js in src/components
import {
  createMuiTheme,
  responsiveFontSizes
} from "@material-ui/core/styles"

let theme = createMuiTheme({
  typography: {
    fontFamily: [
                  "Work Sans",
                  "serif"
                ].join(","),
    fontSize:   18,
  }
})

// To use responsive font sizes, include the following line
theme     = responsiveFontSizes(theme)

export default theme
  1. Now that you've the theme export, you can use it in your components.

  2. Import theme on to your components. Let's say <Layout /> is your main component.

// src/components/layout.js

/**
 * External
 */
import React from "react"
import PropTypes from "prop-types"
import {
  ThemeProvider
} from "@material-ui/styles"
import { Typography } from "@material-ui/core"

/**
 * Internal
 */
import theme from "./theme"

const Layout = ({ children }) => {

  return (
    <>
      <ThemeProvider theme={theme}>
        <Typography variant="body1">Hello World!</Typography>
      </ThemeProvider>
    </>
  )
}
  1. To use Google font in other components, just use
<Typography ...>Some Text</Typography> 

As long as these components use as their parent, these components will continue to use the Google Font. Hope this helps.


Old Answer:

Place your text in the Typography component to reflect the Google Font you installed via npm

import { Typography } from "@material-ui/core"

Assume you have some text in <AppBody>

<AppBody>
    Hello World!
</AppBody>

The above text should now be changed to

<AppBody>
    <Typography variant="body1">Hello World!</Typography>
</AppBody>

Refer Material UI docs for the different variants.

like image 44
Maria Daniel Deepak Avatar answered Oct 18 '22 01:10

Maria Daniel Deepak


I have define my font in main CSS file(index.css)

@font-face {
    font-family: 'mikhak';
    src: url(./fonts/mikhak.ttf) format("truetype")
}

and then in the App.tsx I added theme

const theme = createTheme({
    typography: {
        fontFamily: 'mikhak, Raleway, Arial',
    }
});
    

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

Note that it is for Typography components.

like image 1
Amir Mehrnam Avatar answered Oct 18 '22 03:10

Amir Mehrnam