Multi Language Settings
Let's add the German language.
-
Create a new file
src/locales/gr/translation.json
{ "Menu": "Speisekarte", "Orders": "Aufträge", "Customers": "Kunden", "Sellers": "Verkäufer", };
-
update the below code in the
src/i18n.js
file.
import i18n from "i18next"; import translationGr from "./locales/gr/translation.json"; const resources = { gr: { translation: translationGr } }; const language = localStorage.getItem("I18N_LANGUAGE"); if (!language) { localStorage.setItem("I18N_LANGUAGE", "en"); // replace "en" to "gr". } i18n .use(detector) .use(initReactI18next) // passes i18n down to react-i18next .init({ resources, lng: localStorage.getItem("I18N_LANGUAGE") || "en", // replace "en" to "gr" to set the gr language as default. fallbackLng: "en", // use en if detected lng is not available keySeparator: false, // we do not use keys in form messages.welcome interpolation: { escapeValue: false, // react already safes from xss }, });
The translationGr JSON originates from the file located at
src/locales/gr/translation.json
. -
Now add the new option of German language in the
topbar language dropdown menu
src/components/CommonForBoth/TopbarDropdown/LanguageDropdown.js
in file. -
You must have to write all text like
{props.t('Search_keyword')}
to make it working with all languages. Also make sure to add new words in all other language filessrc/locales/language/translation.json
.
// i18n
import { withTranslation } from "react-i18next";
const LanguageDropdown = () => {
// Declare a new state variable, which we'll call "menu"
const [selectedLang, setSelectedLang] = useState("");
const [menu, setMenu] = useState(false);
useEffect(() => {
const currentLanguage = localStorage.getItem("I18N_LANGUAGE");
setSelectedLang(currentLanguage);
}, [])
const changeLanguageAction = lang => {
//set language as i18n
i18n.changeLanguage(lang);
localStorage.setItem("I18N_LANGUAGE", lang);
setSelectedLang(lang);
}
const toggle = () => {
setMenu(!menu);
}
return (
<Dropdown isOpen={menu} toggle={toggle} className="d-inline-block">
<DropdownToggle className="btn header-item " tag="button">
<img
src={get(languages, `${selectedLang}.flag`)}
alt="Skote"
height="16"
className="me-1"
/>
</DropdownToggle>
<DropdownMenu className="language-switch dropdown-menu-end">
{map(Object.keys(languages), key => (
<DropdownItem
key={key}
onClick={() => changeLanguageAction(key)}
className={`notify-item ${selectedLang === key ? "active" : "none"
}`}
>
<img
src={get(languages, `${key}.flag`)}
alt="Skote"
className="me-1"
height="12"
/>
<span className="align-middle">
{get(languages, `${key}.label`)}
</span>
</DropdownItem>
))}
</DropdownMenu>
</Dropdown>
)
}
export default withRouter(withTranslation()(LanguageDropdown));