Switching language change button to a dropdown

I have implemented i18n into my app and the only way i found to implement the language switch was with a button for every language, like this:

        <div>
          {Object.keys(lngs).map((lng) => (
            <button key={lng} style={{ fontWeight: i18n.resolvedLanguage === lng ? 'bold' : 'normal' }} type="submit" onClick={() => i18n.changeLanguage(lng)}>
              {lngs[lng].nativeName}
            </button>
          ))}
        </div>

i wanna switch it to a dropdown menu, can someone help?

Upvotes: 0

Views: 1378

Answers (2)

David
David

Reputation: 770

If you just need a dropdown here is one option. You can create an array of languages to map through and display/set on change.

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [selectedLanguage, setSelectedLanguage] = useState('en');

  const languages = [
    { code: 'en', name: 'English' },
    { code: 'fr', name: 'French' },
    { code: 'es', name: 'Spanish' },
    // More languages
  ];

  const handleChangeLanguage = (event) => {
    setSelectedLanguage(event.target.value);
    // You should put this into a context so the whole app will be able to access it and avoid prop drilling
  };

  return (
    <>
      <select value={selectedLanguage} onChange={handleChangeLanguage}>
        {languages.map((language) => (
          <option key={language.code} value={language.code}>
            {language.name}
          </option>
        ))}
      </select>
    </>
  );
}

Upvotes: 0

Raktim Kashyap
Raktim Kashyap

Reputation: 1

create a state and set it to default locale:

const [selectedLanguage, setSelectedLanguage] = useState(<defaultLang>);

use the select element to choose from the available locales:

<div>
  <select value={selectedLanguage} onChange={handleLanguageChange}>
    <option value="">Select an option</option>
    {Object.keys(lngs).map((locale) => (
      <option key={locale.id} value={locale}>
        {locale.nativeName}
      </option>
    ))}
  </select>
</div>

for the handleLanguageChange function:

 const handleLanguageChange = (event) => {
    const lang = event.target.value;
    setSelectedLanguage(lang.nativeName);
    i18n.changeLanguage(lang)
 };

Please make necessary changes in this code according to your usecase and check if this works for you. :)

Upvotes: 0

Related Questions