What's the best way to implement a font family in a React component?

I'm currently attempting to implement the font found at:

https://fonts.google.com/specimen/Source+Code+Pro

After downloading the font into my directory, it appears as shown in this image: enter image description here

This is how I have it set up:

<Box sx={{paddingBottom: '4%'}}>
     <AppWindow id='AppWindow'/>
</Box>

I initially tried using

sx={{fontFamily: 'Source Code Pro'}}
without success, indicating that the local files may not have been imported correctly.

I then attempted an import solution:

@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap');

#AppWindow{font-family: 'Source Code Pro'};

However, this did not work either. The only way I was able to somewhat get the font working was by using:

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

The issue with this approach is that it changes the font for everything.

Another method I explored involved modifying the theme within theme.js:

import "@fontsource/SourceCodePro/300.css"

temp:{
  fontFamily: 'Source Code Pro'
}

Yet again, I suspect there might have been issues with importing the local files correctly. Any assistance would be greatly appreciated.

Answer №1

If you prefer, you can use the webfontloader library as an alternative. Start by downloading it:

yarn add webfontloader # Alternatively, npm i webfontloader

Next, import it into the component where you want to utilize the font:

import WebFont from 'webfontloader';

When the component mounts, the desired fonts will be loaded using the useEffect hook. Specify the font you wish to download in the code block:

useEffect(() => {
  WebFont.load({
    google: {
      families: ['Your Font Name']
    }
  });
}, []);

Afterwards, you can apply the font by either using className and adjusting your CSS or implementing inline styling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for dynamically updating a variable's state within a render function?

I'm currently working on a project for my class where we are tasked with creating a website using React. Unfortunately, neither myself nor my group members have been able to figure out how to render a function in a variable state and make it dynamic. ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

SSL/HTTPS issues impacting Server-Sent Events (SSE)

Greetings, I am currently in the process of developing a React web application that is designed to receive SSE data from an Express server working with Nginx. SERVER.JS const express = require('express'); const bodyParser = require('body-p ...

What is the best way to include multiple HTML elements along with their attributes in a React array?

I need to include HTML elements with class properties in a React array. colArray1.push( <div className={classes.imgContainer} key={875643}>); However, I am encountering an error message saying "Cannot read property 'imgContainer' of u ...

Customizing Background Color of Bottom Tab Content Container in React Native

Hey there, I need some help with changing the color of the bottom tabs screens. They are currently gray by default (as shown in the image) and I want them to be white. I've tried using tabBarStyle but it doesn't seem to work. If anyone has any i ...

Upon the initial page load, the create-react-app is rendered without any content

I created an app that initially shows a blank page upon startup, but strangely it loads correctly when the page is refreshed. Here is my code: index.js import React from 'react'; import ReactDOM from 'react-dom'; import './Asset ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

Having difficulty integrating a specific NPM package with a React project

I'm trying to incorporate the TagCloud package into my React application, but I'm encountering some difficulties. Despite not receiving any error messages in the console, the TagCloud component simply doesn't show up on the page. Interesting ...

Place a fresh banner on top of the Ionicon icon

I recently started using Ionicons from and I am not too familiar with css. My question is, can a banner that says 'new' be overlaid on the top right corner of the Icon? Is there a simple or standard method to achieve this? (whether it's an ...

What is the proper HTML tag and syntax used for adding a text box within the content of a webpage?

Question about HTML: How can I add a text box or block to an HTML page that is filled with plain text? I want the text box to align to the right and be surrounded by the plain text, essentially wrapping around it. I also need to specify the dimensions of ...

Getting a single item from nested objects within arrays

Having retrieved data from an open API, I encountered an issue when trying to display an image in my browser. The Images array contains 3 image URLs, and despite using the map method on arrays, calling the first object [0] did not yield the desired result. ...

Exploring Bottom Tab Styling in React Navigation

How can I achieve a similar style for the bottom tab like the one shown in this model? View Model <HomeTabs.Navigator screenOptions={({route})=>({ tabBarIcon: ({color, size})=>{ const {name} = icons[route.name ...

Is it just me, or does `position: fixed;` not actually fix the element to the top?

I'm experiencing an issue where the element isn't fixed to the top of the page, despite using the position: fixed; property. I've tried several solutions including: Setting a z-index of 9999 Wrapping all elements in a single container (.fi ...

Tips for aligning a div below another div nested within a separate container

Can I position div#d2 directly beneath the div#d1 container according to the code below, instead of positioning it outside the height of the wrapper? #wrapper { height: 100%; display: flex; background-color: steelblue; align-items: center; min ...

Guide to comparing the contents of two text fields and highlighting the altered characters using ReactJS

Is there a way to compare the contents of two Material-UI textfields and identify the characters that have changed in both? I came across a similar question, but it was specifically for ReactJS rather than C# Windows Forms: How can you highlight the chara ...

How to Alter the Color of a Hyperlink in HTML

I've been working on an angular2 application and I'm using a hyperlink to trigger a method that opens a small popup window. I've tried different methods to change the color of the link when it's clicked, but so far none have worked. Th ...

Having difficulty passing the new state value using props in ReactJS

I am facing an issue with sending state values from parent to child components. Initially, the state value is empty but after making an API call, the state value gets updated. However, the props in my child component are still stuck with the initial empty ...

Is there a way to make a Bootstrap grid with four columns span across two rows in the second column?

How can I create a Bootstrap grid with four columns where the second column spans two rows? Hello, I am looking for help to achieve a portfolio grid layout with 4 columns (refer image here) and have the second column span 2 rows. I plan to include images ...

Enhance the responsiveness of full-screen pop-ups

My current project involves creating a full-screen pop-up for a specific application. /* Custom Full Screen Popup */ .fullscreen-popup { position: fixed; top: 0; ...

The challenge of integrating Strapi with React and Material UI data tables

Recently, I started working with React and set up a backend using Strapi. After testing the GraphQL query and confirming that it retrieves values for all nodes, I encountered an issue while populating a Material UI DataGrid component in React. Most of the ...