[QUESTION] Cannot read properties of undefined (reading 'value') - i18n locales
belkocik opened this issue · comments
Marcin Niedbalec commented
I'd like to change the locale: "en" and "pl" but I occured an error Cannot read properties of undefined (reading 'value')
here
const changeLanguage = e => {
> 63 | const locale = e.target.value
| ^
64 | router.push(router.pathname, router.asPath, { locale })
65 | }
changing the locale logic
const Navbar = props => {
const { path } = props
const router = useRouter()
const { locale } = router
const t = locale === 'en' ? en : pl
const changeLanguage = e => {
const locale = e.target.value
router.push(router.pathname, router.asPath, { locale })
}
Here is my Select component
<Select
onChange={changeLanguage}
defaultValue={locale}
width="74px"
display={{ base: 'none', md: 'inline-block' }}
variant="outline"
cursor="pointer"
ml="30px"
options={[
{
label: 'EN',
value: 'en'
},
{
label: 'PL',
value: 'pl'
}
]}
/>
the previous one chakra's one orginal which worked
<Select
onChange={changeLanguage}
defaultValue={locale}
width="74px"
display={{ base: 'none', md: 'inline-block' }}
variant="outline"
cursor="pointer"
ml="30px"
_focus={{
boxShadow: 'teal'
}}
>
<option value="en">EN</option>
<option value="pl">PL</option>
</Select>
Chris Sandvik commented
Unlike the Chakra UI Select which is a wrapper for the native HTML <select>
element, this component doesn't return a change event (with how you're getting e.target.value
). It instead just returns the object itself from your list of options. So in order for this to work right, you'll need to change your changeLanguage
function like so:
/**
* newLanguage = {
* label: 'EN',
* value: 'en'
* }
*/
const changeLanguage = newLanguage => {
const locale = newLanguage.value; // <-- just .value not .target.value
router.push(router.pathname, router.asPath, { locale })
}