πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

How to switch between languages on a landing page using Next JS

4 replies
Last updated: Oct 13, 2021
Hi everybody. I have set up a landing page that could have content of two languages, norwegian and english. I'm able to query the content of the language I wanted, but I don't know how to switch between languages on the front end (I'm using Next JS). Any suggestions how to solve it? Thanks in advanced. Here is my code:

import React from "react";
import Link from "next/link";
import { Image, Text } from "@chakra-ui/react";
import { BrandTitle, ScreenContainer } from "src/components";
import { groq } from "next-sanity";
import { getClient } from "lib/sanity.server";

const postQuery = groq`
*[_type =='landingPage' && _lang == $lang ]{
    titlePartOne,
    titlePartTwo,
    availableLanguage,
    textContent,
    _lang,
    "image": mainImage.asset->url,
    "caption": mainImage.caption,
}
`;

const language = "no"; //switch value. en_GB for english

export default function Home({ data }) {
  const {
    availableLanguage,
    image,
    caption,
    textContent,
  } = data?.site[0];
  const { titlePartOne, titlePartTwo } = data?.site[1];


  return (
    <ScreenContainer>
      <BrandTitle titlePartOne={titlePartOne} titlePartTwo={titlePartTwo} />
      <Image src={image} alt={caption} />
      <Text>{textContent}</Text>
      <Link href="#">{availableLanguage}</Link>
    </ScreenContainer>
  );
}

export async function getStaticProps({ preview = false }) {
  const site = await getClient(preview).fetch(postQuery, {
    lang: language,
  });
  return {
    props: {
      preview,
      data: { site },
    },
  };
}
Oct 12, 2021, 7:43 AM
Hi. I'm looking to change the language value by clicking a button. Sending the value on the client side to the
getStaticProps
Is there any example projects on how to switch between languages by clicking a button?
Oct 13, 2021, 6:07 AM
Hi. I'm looking to change the language value by clicking a button. Sending the value on the client side to the
getStaticProps
Is there any example projects on how to switch between languages by clicking a button?
Oct 13, 2021, 6:07 AM
Hi again. I just figure out that I forgot to define locales in the
next.config.js file
. Thanks for your response.
Oct 13, 2021, 8:06 AM
Glad you got it sorted out!
Oct 13, 2021, 5:30 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?