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

What is the reason for the child component having a greater number of props compared to the parent component

I am facing an issue with my parent component and child component in React. The child component seems to have more props data than the parent component. Parent component: import React, { Component} from 'react'; import { Link } from 'react ...

Generate a list of items in typescript, and then import them into a react component dynamically

I have a variable that stores key/value pairs of names and components in a TypeScript file. // icons.tsx import { BirdIcon, CatIcon } from 'components/Icons'; interface IconMap { [key: string]: string | undefined; } export const Icons: IconM ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

How can I apply a blurred effect to the background image of a jumbotron in Bootstrap-vue without affecting the clarity of the text overlay

I need help figuring out how to blur the background image of my jumbotron without blurring the text on top. <b-container fluid class="text-center"> <div> <b-jumbotron class="jumbotron"> <p style=& ...

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

Is there a method available to retrieve the data values stored within these objects?

Looking at the image below, I have data that includes a Data array in JSON format. The Data array contains key values such as condition_type and other related values. In order to extract individual values, I am using the following code: const submitcode ...

Setting a state variable in the parent component of a React Route: A step-by-step guide

Implementing routing in my app has been an enjoyable experience, but I am facing difficulties when it comes to setting a page title in the parent based on the screen being rendered by Route. Currently, I have the following setup: class App... setTitle(t ...

What is the best way to access bootstrap col and row styles without needing to import the entire framework?

I am currently in the process of developing a react app using styled-components and I am looking to design a component that mimics the functionality of the col col-x classes from bootstrap. Additionally, I also want to create another component for the row ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

Delayed hover dropdown navigation menu powered by Bootstrap

I am experimenting with creating a bootstrap dropdown menu that opens and closes on hover, but only after a 250ms delay for desktop devices. Custom JavaScript: $(document).ready(function() { if ($(window).width() > 767) { $(".dropdown-toggl ...

Exploring the discrepancies in utilizing the i18n library versus directly incorporating locale from JSON in vue.js

Recently, I decided to incorporate Chinese language into my Vue app. To achieve this, I loaded the entire JSON text into Vuex and utilized the stored text directly, instead of relying on an i18n library. I'm curious to know if there are any potential ...

What is the process for incorporating styles into an external widget?

I am currently navigating my way through NextJS and attempting to incorporate a bespoke stylesheet into my code using a third-party widget. Unfortunately, I have hit a roadblock in this process. The names I have assigned to the style sheet align with what ...

Learn how to effectively transfer parameters between two React components

I am currently working on a component that looks like this: pays11 = iconAllemagne; pays12 = iconHungrier; score11_12='2 - 2'; bonus11_12 = 'x0'; render() { return ( <Page> ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Can React Hooks API be used in TypeScript without using JSX?

After attempting to convert the JSX version of the React Hooks API demo into one without JSX, following the guidelines provided in react-without-jsx documentation, I ended up with the code below: import React, { useState } from 'react'; import R ...

Uninterrupted movement within a picture carousel

Seeking a way to create a smooth transition in an image slider with sliding dividers using continuous switching when clicking previous/next buttons. Currently, the dividers replace each other from far positions. Any ideas on achieving a seamless single mov ...

React createElement function does not include string children when there are multiple children present within the inner HTML

Currently, I am utilizing React.createElement(...) to dynamically produce a basic react website using data from a JSON file. The JSON file consists of an array of JSON objects that represent elements and their respective children. An individual element&ap ...

Resetting state upon ISR revalidation in Next.js: a step-by-step guide

Picture a scenario where I have a Next.js application that utilizes ISR to display temporary content on the homepage. This content is interactive, and I intend to manage the client state in a Context API. Every 24 hours, I want to refresh this interactive ...

Expanding the full width of the bootstrap navbar

Let's cut to the chase - I'm working with Bootstrap 4 and trying to make my navbar fill the entire width (excluding margins). I know this question has been asked before, so I checked out a post here which suggested using the .nav-fill class, but ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...