-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is it possible to select a language using Select with options? #62
Milestone
Comments
Yes, though how to do so is outside this repo's scope. onclick change the query param |
An example with mui could look like that: import { useRouter } from "next/router"
import { useEffect, useState } from "react"
import { useLanguageQuery, useTranslation } from "next-export-i18n"
// Import the useTranslation hook to provide translation of the language-label.
const { t } = useTranslation();
// Use the custom useLanguageQuery hook to fetch the current language query parameter e.g. {lang: "en"}.
const [query] = useLanguageQuery();
// Initialize a state variable 'language' with an empty string as its default value.
const [language, setLanguage] = useState("");
// Use the useRouter hook from Next.js to access the router object.
const router = useRouter();
// Effect hook to update the 'language' state if it's empty and there's a language query parameter.
useEffect(() => {
// only update language if the 'language' state is still empty and if there's a 'lang' query parameter.
if (language === "" && query?.lang) {
// Update the 'language' state with the value of the 'lang' query parameter (to set the browsers preferred language as the current selected).
setLanguage(query?.lang);
}
// The effect will run whenever the 'language' state or the 'lang' query parameter changes.
}, [language, query?.lang]);
// Handler function for language change events.
const handleChange = (event) => {
// Extract the new language value from the event object.
const newLanguage = event.target.value;
// Update the 'language' state with the new value.
setLanguage(newLanguage);
// Use the router to navigate to the current path but with an updated 'lang' query parameter.
router.push(
{
pathname: router.pathname,
query: { lang: newLanguage }, // Update the 'lang' query parameter with the new language.
},
undefined,
{ shallow: true } // use shallow routing, to not send an unnecessary request to the server.
);
} <FormControl>
<InputLabel id="select-language-label">{t("language")}</InputLabel>
<Select
labelId="select-language-label"
id="language-select"
value={language}
label={t("language")}
onChange={handleChange}>
<MenuItem value="de">Deutsch</MenuItem>
<MenuItem value="en">English</MenuItem>
<MenuItem value="ru">Pусский</MenuItem>
</Select>
</FormControl> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example I need to use Select options like this:
The text was updated successfully, but these errors were encountered: