pytha goras
pytha goras

Reputation: 21

Gatsby language localization (language change using one button)

I have this code which enables the language switch between English and German using two separate buttons (anchor tags). The problem is I have to enable this switch using only one button, but I just can't wrap my head around it.

Here is the "language.js" component:

import { IntlContextConsumer, changeLocale } from "gatsby-plugin-intl"

const languageName = {
  en: "English",
  de: "Deutsch",
}

const Language = () => {
  return (
    <div>
      <IntlContextConsumer>
        {({ languages, language: currentLocale }) =>
          languages.map(language => (
            <a
              key={language}
              onClick={() => changeLocale(language)}
              style={{
                color: currentLocale === language ? `yellow` : `white`,
                margin: 10,
                textDecoration: `underline`,
                cursor: `pointer`,
              }}
            >
              {languageName[language]}
            </a>
          ))
        }
      </IntlContextConsumer>
    </div>
  )
}

export default Language

If you need any other component please let me know.

Thanks in advance for your response. :)

ps. Localization is done without a i18 implementation.

Upvotes: 1

Views: 910

Answers (1)

Pierre Monico
Pierre Monico

Reputation: 1100

Following simple example should yield the expected result when only using two languages like in your snippet. If you add languages to your configuration then it will always display all languages except the current locale.

import React from "react"
import { IntlContextConsumer, changeLocale } from "gatsby-plugin-intl"

const languageName = {
  en: "EN",
  de: "DE",
}

const LanguageToggle = () => {
  return (
    <div>
      <IntlContextConsumer>
        {({ languages, language: currentLocale }) =>
          languages.map(language => {
            if (language != currentLocale) {
              return (
                <a key={language} onClick={() => changeLocale(language)}>
                  {languageName[language]}
                </a>
              )
            }
          })
        }
      </IntlContextConsumer>
    </div>
  )
}

export default LanguageToggle

Upvotes: 1

Related Questions