A guide on switching font family based on locale changes (language in i18n) within Next.js

My application supports multiple languages and allows users to switch between two languages using a select input. Additionally, I want to change the font-family based on the selected language.

In my _app.js file:

const {locale} = useRouter();
useEffect(() => {
  if(locale === "ur"){
    import("../styles/urdoFont.css");
  }else{
    import("../styles/persianFont.css");
  }
}, [locale]);

And in the header component:

<Link 
   href={{
      pathname: '/',
                    }}
      as={`/`}
      locale="fa"
 >
   <a>
     <Image
        src="/image/iran.svg"
        alt=""
        width="40"
        height="40"
     />
   </a>
 </Link>
 <Link 
      href={{
         pathname: '/ur',
      }}
      as={`/ur`}
      locale="ur"
    >
      <a>
        <Image
          src="/image/pakistan.svg"
          alt=""
          width="40"
          height="40"
        />
      </a>
 </Link>

Answer №1

After experimenting, I found a solution that works well for me using Next 13 and @next/font. This method should be compatible with any version supporting @next/font

Here's the step-by-step process:

    import { googleFont1, googleFont2 } from "@next/font/google"
    import { useRouter } from "next/router.js"
    
    const font1 = googleFont1({
    ...options
    })
    
    const font2 = googleFont2({
    ...options
    })
    
    function App({ Component, pageProps }) {
      //checking the current locale using the built-in router
      const { locale } = useRouter()
    
      return (
        <main
          //conditional statement based on the current locale
          className={`${
            locale === "en" ? 
            font1.className : 
            font2.className
          }`}
        >
          <Component {...pageProps} />
        </main>
      )
    }
    
    export default App

Both fonts are loaded upon page load with this approach, but only one is applied to the tag at a time.

If the user switches languages, the applied font will change automatically.

For more information, you can refer to the @next/font documentation. It has been incredibly beneficial in saving development time and improving page load speed!

I trust this explanation proves useful!

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

Learn how to retrieve multiple checkbox values in reactjs by utilizing antd checkbox

I have a table displaying student information and I want to be able to select multiple checkboxes. However, currently, I can only select one checkbox at a time. How can I achieve selecting multiple checkboxes? class StudentTable extends React.Compo ...

The setInterval timer is malfunctioning within the render() method of ReactJS

In my React component, I have a countdown timer that starts at 10 seconds. If the backend data is received within this time frame, the timer stops. If not, it will continue counting down to 0 and then refresh the page, repeating the cycle until the data is ...

Creating a dynamically changing AppBar component in material-ui-next React that responds to scroll events

Following the Material Design guidelines, the top app bar should exhibit specific behavior: When scrolling, the top app bar can [...] undergo the following changes: - Scrolling upwards hides the top app bar - Scrolling downwards reveals the top ...

Modify the directory (app) within the Next.js app router

Hey there, I am looking to change the default app-router folder (app) in Nextjs I have tried searching for a solution but couldn't find one I want to rename it from: src/app/layout.tsx to src/nextapp/layout.tsx Does anyone know how to do this? I&ap ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

Ensure that the form is submitted when a checkbox is clicked, while also maintaining the native browser

My form contains a text input field and a checkbox. The text input must not be left empty when the form is submitted, which is why the required attribute is used. I want the form to be submitted every time the checkbox is clicked, while still maintaining ...

Encountering an issue with a Next.js app where it has become stuck during execution, the command "npm run dev

After successfully creating a simple next.js app and starting it with npm run dev, I encountered an issue when trying to start it for the second time: enter image description here Even after attempting to create a new project, the problem persisted. Inte ...

Tips for reducing the gap between the border and text within a Textfield element in Material UI

Check out my UI Working on my Reactjs project and grappling with styling the material ui Textfield component. const styles = theme => ({ input: { width: 30, height:30, marginTop:10, fontSize:7, padding:0, ...

"Discovering the method to showcase a list of camera roll image file names in a React Native

When attempting to display a list of images from the user's camera roll, I utilized expo-media-library to fetch assets using MediaLibrary.getAssetsAsync(). Initially, I aimed to showcase a list of filenames as the datasource for the images. Below is m ...

Why does the devServer port ignore the loading of webpack chunks?

I'm attempting to implement dynamic imports using React.lazy. The code is fairly straightforward: import React, { Component, Suspense, lazy } from 'react'; const LazyComponent = lazy(() => { return import('./lazy'); }); c ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

Attempting to provide images that are dynamically downloaded in real-time using Express Middleware

I'm facing a challenge with express and middleware. My goal is to serve an image from disk, but if it's not there, download it from an external server and then display it. Subsequent requests for the same image should be served from disk. Downlo ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

Is generateStaticParams not compatible with Nextjs 13's "not-found" feature?

I'm currently utilizing the "generateStaticParams" feature in Next.js 13 to handle 404 errors for routes that don't correspond with a specific set of IDs retrieved from another function. Here's an example of how I'm implementing it: exp ...

Simultaneous debounce and setting of text data is not occurring

Despite my efforts, I am facing issues with implementing the debounce feature and retaining the value of a textbox that I type. Interestingly, if I remove setMyval(e.target.value); on line #20, the debounce functionality works smoothly but the typed value ...

excessive server memory usage in a Next.js project

We are currently working on a Next.js project which is a builder project where web pages load from JSON data and users interact through the builder and dashboard. Our user base is not large, with usually 2-15 users actively engaging in the dashboard at any ...

What causes material-ui to consume excessive amounts of space?

My React project is being bundled using webpack, with a dependency on material-ui for the following components: material-ui/Dialog material-ui/styles/getMuiTheme material-ui/styles/MuiThemeProvider material-ui/FlatButton material-ui/TextField The webpack ...

Re-establishing the socket channel connection in a React application after a disconnection

There are several solutions to this issue, but none of them seem to be effective for me. The existing solutions are either outdated or do not meet my needs. I am facing a problem where I have a large amount of data being transferred from the server to the ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...