Z
Z
Zhanna_K2020-10-14 12:03:53
React
Zhanna_K, 2020-10-14 12:03:53

How to properly include fonts in React (Material UI)?

I'm trying to connect files with fonts, so far without success: I

read the following in the documentation:
5f86be7a6b017707397205.png
What loader should I use and where should I write it?

1) I create a custom theme, I include fonts in it

import { createMuiTheme } from "@material-ui/core/styles";
import blue from "@material-ui/core/colors/blue";
import yellow from "@material-ui/core/colors/yellow";
import MontserratWoff from "./fonts/Montserrat-Regular.woff";
import MontserratEot from "./fonts/Montserrat-Regular.eot";
import MontserratOtf from "./fonts/Montserrat-Regular.otf";
import MontserratTtf from "./fonts/Montserrat-Regular.ttf";

const montserrat = {
  fontFamily: "Montserrat",
  fontStyle: "normal",
  fontDisplay: "swap",
  fontWeight: 400,
  src: `
    url(${MontserratWoff}) format('woff')
    url(${MontserratEot}) format('eot')
    url(${MontserratOtf}) format('otf')
    url(${MontserratTtf}) 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",
};

const theme = createMuiTheme({
  palette: {
    primary: {
      light: blue[500],
      main: blue[200],
      dark: blue[900],
      contrastText: "#fff",
    },
    secondary: {
      light: yellow[300],
      main: yellow[300],
      dark: yellow[800],
      contrastText: blue[900],
    },
  },
  typography: {
    fontFamily: "Montserrat",
  },
  overrides: {
    MuiCssBaseline: {
      "@global": {
        "@font-face": [montserrat],
      },
    },
  },
  spacing: [0, 4, 8, 16, 32, 64],
});

export default theme;

2) I send this topic through the provider:
function App() {
  return (
    <div className='appWrapper'>
      <div className='skew'></div>
      <ThemeProvider theme={theme}>
        <HeaderContainer />
        <Switch>
          <Route exact path='/' component={SplashPage}></Route>
          <Route exact path='/contacts' component={Contacts}></Route>
          <AuthRoute
            exact
            path='/register'
            component={RegistrationPageContainer}
          ></AuthRoute>
          <AuthRoute
            exact
            path='/auth'
            component={authPageContainer}
          ></AuthRoute>
          <ProtectedRoute
            exact
            path='/projects'
            component={ProjectsPageContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/projects/:id'
            component={ProjectContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/tasks/:id'
            component={TasksContainer}
          ></ProtectedRoute>
          <ProtectedRoute
            exact
            path='/myprojects'
            component={MyProjectsContainer}
          ></ProtectedRoute>
        </Switch>
      </ThemeProvider>
    </div>
  );
}
export default App;


3) In the components I write like this:
const useStyle = makeStyles((theme) => styles(theme))

where styles is a function that returns an object with styles.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kilot5791, 2021-01-30
@kilot5791

Can anyone help, I connected the fonts in the following way:
1) I created a file with a custom theme theme.jsx

import { createMuiTheme } from '@material-ui/core/styles';

// Здесь импортируем шрифты
import pathRegular from './fonts/Montserrat-Regular.woff2';
import pathBold from './fonts/Montserrat-Bold.woff2';
import pathMedium from './fonts/Montserrat-Medium.woff2';
import pathSemiBold from './fonts/Montserrat-SemiBold.woff2';
import pathExtraBold from './fonts/Montserrat-ExtraBold.woff2';

// С помощью класса мы будем создавать объекты.(чтобы под каждый шрифт не писать объект вручную, может быть есть какой то способ получше, но я новичок в js)
class Font {
    constructor(fname, fstyle, fweight, furl) {
        this.fname = fname;
        this.fstyle = fstyle;
        this.fweight = fweight;
        this.furl = furl;

        return {
            fontFamily: this.fname,
            fontStyle: this.fstyle,
            fontDisplay: 'swap',
            fontWeight: this.fweight,
            src: `
                local(${this.fname}),
                url(${this.furl}) 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',
        }
    }
};

const montserratRegular = new Font('Montserrat', 'normal', 400, pathRegular);
const montserratBold = new Font('Montserrat', 'normal', 700, pathBold);
const montserratSemiBold = new Font('Montserrat', 'normal', 600, pathSemiBold);
const montserratExtraBold = new Font('Montserrat', 'normal', 800, pathExtraBold);
const montserratMedium = new Font('Montserrat', 'normal', 500, pathMedium);

export const theme = createMuiTheme({
    typography: {
        fontFamily: 'Montserrat',
        fontSize: 24,
        body1: {
            fontWeight: 400
        },
        h1: {
            fontSize: 32,
            fontWeight: 700,
            color: '#444'
        } 
    },
// Если используется СssBaseline то для него нужно изменить шрифт глобально, если не используем то код ниже не пишем
    overrides: {
        MuiCssBaseline: {
          '@global': {
            '@font-face': [montserratRegular, montserratBold, montserratSemiBold, montserratExtraBold, montserratMedium],
          },
        },
      },
});

export default theme;

2) Import the theme into our application:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';

import './index.css';
import theme from './theme'

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

3) The App.js application itself looks like this:
import React from 'react'
import { Typography } from '@material-ui/core';

function App() {
  return (
    <div className="App">
      <Typography>Almost before we knew it, we had left the ground.</Typography>
      <Typography variant='h1'>Almost before we knew it, we had left the ground.</Typography>
    </div>
  );
}

export default App;

PS. Despite the fact that the documentation says that you can import fonts in ttf, woff and woff2 format, ttf fonts are not connected to me with this code, I have not tried woff

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question