Implementing Google Fonts into Next.js with the combination of Sass, CSS, and Semantic UI React

I have set up my next.config.js file with the following configuration:

const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withSass(withCss({
  webpack (config) {
    config.module.rules.push({
      test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
          publicPath: './',
          outputPath: 'static/',
          name: '[name].[ext]'
        }
      }
    })

    return config
  }
}));

This setup allows me to efficiently run semantic ui css files.

However, I'm currently facing a problem. I am unable to import Google font URLs successfully. I attempted to download the ttf file into my file path and reference it using the @import SCSS function. Unfortunately, when doing so, I receive a GET http://localhost:3000/fonts/Cabin/Cabin-Regular.ttf net::ERR_ABORTED 404 (Not Found) error

Here is how I am trying to use the Google font:

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

$font-size: 100px;
.example {
  font-size: $font-size;
  font-family: 'Cabin', sans-serif;
}

In addition to setting up this configuration, I have also installed the necessary npm dependencies:

"@zeit/next-css": "^1.0.1",
"@zeit/next-sass": "^1.0.1",
"file-loader": "^2.0.0",
"next": "^7.0.2",
"node-sass": "^4.9.4",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.83.0",
"url-loader": "^1.1.2"

Answer №1

In the latest version of Next.js 9.3, you have the ability to easily incorporate Google Fonts by copying the @import statement:

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

You can then paste this snippet into a CSS file, such as styles/fonts.css:

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

.jost {
  font-family: 'Jost', sans-serif;
}

Next, import this CSS file into your global _app.js file like so:

import `../styles/fonts.css`

Now, you will have universal access to the defined class with the Google Font across all Next.js pages.

Answer №2

One solution I recommend is utilizing fonts directly from Google by customizing the _app.js file and including a <link rel="stylesheet" /> in the <Head />

Check out this sample _app.js for reference:

import React from 'react';
import App, { Container } from 'next/app';
import Head from 'next/head';

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Cabin"
            rel="stylesheet"
            key="google-font-cabin"
          />
        </Head>

        <Component {...pageProps} />

        <style global jsx>{`
          body {
            font-family: 'Cabin', sans-serif;
          }
        `}</style>
      </Container>
    );
  }
}

Answer №3

 class EnhancedApp extends App {
  render() {
    const { ChildComponent } = this.props
    return (
          <React.Fragment>
            <ChildComponent {...pageProps} />

            <style jsx="true" global>{`

              @import url('https://fonts.googleapis.com/css?family=Barlow');

              body {
                margin: 0;
                font-family: 'Barlow', sans-serif;
              }

            `}</style>

          </React.Fragment>
        </Provider>
      </Container>
    )
  }
}

Using the Google Fonts URL in styled-jsx did the trick for me!

Answer №4

According to the most recent documentation, you now have the ability to include global CSS by updating the _app.js file and importing your CSS styles. Follow the steps outlined below:

  1. Create a custom _app.js file in the pages directory following the instructions in the documentation.
  2. Add your styles.css file to the pages directory.
  3. Include the styles as shown below:

// _app.js

// Import styles
import './styles.css'

// Function to create custom app
function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

// Export app
export default MyApp

And that's it! These styles from styles.css will be applied to all pages and components within your application. Since stylesheets have a global scope, and to prevent conflicts, make sure to only import them within the _app.js file.

Answer №5

To get it working, I needed to move the files to the static directory. It seems there was a particular configuration for displaying images and fonts in nextjs.

Answer №6

To incorporate Google Fonts or any CDN-linked fonts into your custom functional app, you can follow the steps below:

import Head from 'next/head';

// Custom app as a functional component
function MyApp({ Component, pageProps }) {
  return (
    <>
      <Head>
        <link
          href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600;700&display=swap" rel="stylesheet"/>
      </Head>
      <Component {...pageProps}/>
    </>
  )
}

MyApp.getInitialProps = async ({ Component, ctx }) => {
  let pageProps = {};
  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }

  return { pageProps };
};

// Export app
export default MyApp

You can then apply the font family to the body element using CSS to ensure the font is displayed throughout the website:

body {
  font-family: 'Source Sans Pro', sans-serif;
}

Answer №7

This is my current method for loading external fonts nonblocking. In the head of _document.js:

<script dangerouslySetInnerHTML={{__html: '</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" media="print" onload="this.media=\'all\'" /><script>' }} />
  • Using dangerouslySetInnerHTML and some script manipulation to bypass the onload issue in _document.js until it is resolved

source

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

Ensuring the bottom border of an element extends to the edge of the screen when utilizing a 960 grid in HTML/CSS

I am currently working on creating a website layout using the 960 grid system developed by Nathansmith. I am facing an issue in extending the bottom border of an element to reach till the end of the screen while keeping the element inside a container div. ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Enhance your React Table with a dynamic Material UI context menu

Currently facing difficulties in implementing the Material UI Menu with React Table@v6. I am aiming to display a context menu by right-clicking anywhere within the table (row, td). This functionality is operational. However, my goal is also to consiste ...

Customize Material UI's CssBaseline for individual pages, focusing on altering the background color

In my _app.js file, I have implemented the ThemeProvider and CssBaseline, which successfully pulls in the background color from the theme. However, there are certain pages where I need to override the body background color. By wrapping my page components ...

Invalid anchorEl prop given for MUI component

Currently, I am in the process of developing a mobile menu feature, where upon clicking the menu icon, the menu will be displayed. The code snippet for this functionality is as follows: const StyledMenu = withStyles({ paper: { border: '1px soli ...

Select an option from the navigation bar - the chosen item will remain highlighted

My Navbar code looks like this: <Navbar.Collapse> <Nav> <NavItem eventKey={1} href={`${process.env.PUBLIC_URL}/`}> Blah </NavItem> <NavItem eventKey={1} href={`${process.env.PUBLIC_URL}/SomePage`} ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Customizing checkboxes in React with JSS: A step-by-step guide

I'm currently working on customizing CSS using JSS as my styling solution, which is proving to be a bit complex while following the w3schools tutorial. https://www.w3schools.com/howto/howto_css_custom_checkbox.asp HTML: <label class="container"& ...

Tips for creating a checkbox within a form control or form control label without using a label

Below is the code snippet that showcases my progress so far: <FormGroup> <FormControlLabel control={ <Checkbox checked={isItemSelected} onChange={(event) => handleClick(event, id)} ...

What is the process for utilizing Angular's emulated encapsulation attributes on HTML elements that are dynamically added to an Angular component?

Within my custom Angular component, a third-party library is dynamically adding an HTML element. I am seeking a solution that can apply Angular's encapsulation attributes to these elements regardless of the specific third-party library being used. If ...

Updating user information in MongoDB

I'm encountering an issue while attempting to update a user, and it's showing me this error: https://i.stack.imgur.com/sYDv2.png Despite my best efforts, I haven't been able to find a solution. I've tried using different methods from t ...

Splitting the page into four sections with a unique H layout using CSS styling

Attempting to create an H page layout: body { background-color: grey; background-size: 100%; background-repeat: no-repeat; } html, body { height: 100%; margin: 0px; } .a { float: left; width: 25%; height: 100%; border: 1px solid blue ...

Can a DjangoREST+React project be deployed on a single Google Cloud App Engine instance?

My setup includes a Django backend that interacts with the React.js frontend through REST APIs created with the DjangoREST Framework. In past projects, I've always used separate gcloud projects/app engine instances for Django and React. However, this ...

Having issues with jQuery not functioning on this specific web page across all browsers. The reason behind this puzzling dilemma remains elusive to me

I am experiencing issues with the functionality of my website. The buttons with + signs are meant to be drop-down toggles, and the mini-tabs below them should work as tabs. Additionally, the sample images at the bottom are not loading properly when clicked ...

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

The process of testing the catch part in jest and @testing-library/react

ComponentFile.js <Button onClick={ async e =>{ clearForm(); }} Reset </Button> const clearForm = () => { try{ someRef.current.clearFormData(); const display = document.getElementById("errorDisplayDi ...

The filter on the mobile version is not displaying correctly

When I select a category in the input filter, only items with the same category are displayed when clicked. However, when I click on "Others" on the desktop version, only rows with that category are shown, but on mobile after resizing and filtering, nothin ...

The angular-block-ui feature fails to run my HTML code as a personalized message

I'm looking to enhance my UI by implementing a blocking feature with a spinner display. My attempt involved the following code: blockUI.start("<div class='dots-loader'>Minions are Working!</div>"); // code for fetching data ...