Internacionalización de Idiomas con Next.js y Cookies
Clase 6 de 12 • Curso de Next.js: Internacionalización de Aplicaciones Web con i18n
Contenido del curso
Clase 6 de 12 • Curso de Next.js: Internacionalización de Aplicaciones Web con i18n
Contenido del curso
Christian Diaz Portela Flores
Fernando Quinteros Gutierrez
Carlos Eduardo Magallon Zepeda
Les comparto este language switcher que hice con Next.js y Material-UI. Queda así:
Código:
import React, { FC } from 'react' import { useRouter } from 'next/router' import NextLink from 'next/link' import Link from '@material-ui/core/Link' import Typography from '@material-ui/core/Typography' const LocaleSwitcher = () => { const { locale, asPath: currentPath } = useRouter() return ( <> {locale === 'en-US' ? ( <span style={{ cursor: 'default' }}> <NextLink passHref href={currentPath} locale="es"> <Link> <Typography variant="h5" component="span"> Es </Typography> </Link> </NextLink>{' '} /{' '} <Link component="span" variant="h5" underline="always"> En </Link> </span> ) : ( <span style={{ cursor: 'default' }}> <Link component="span" variant="h5" underline="always"> Es </Link>{' '} /{' '} <NextLink passHref href={currentPath} locale="en-US"> <Link> <Typography variant="h5" component="span"> En </Typography> </Link> </NextLink> </span> )} </> ) } export default LocaleSwitcher
🌐 Detección de idioma automática y next/link
Apuntes
Experiencia de usuario
Next.js detecta el idioma del usuario de forma automatica*
Accept-Language Header HTTP propio del navegador
next.config.jsmodule.exports = { i18n: { localeDetection: false, } }
i18n y next/Link
next/link navegará al locale actualmente activorouter.pushrouter.push( url: string, as?: string, { locale: 'br' } )
<Link href="/br/about-us" locale={ false } />
i18n Cookie
NEXT_LOCALE
import { Fragment, useState, MouseEvent } from 'react' import { useRouter } from 'next/router' import NextLink from 'next/link' import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; export function LanguageSetter(){ const [anchorEl, setAnchorEl] = useState<Element|null>(null); const handleClick = (event: MouseEvent<HTMLButtonElement>) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const router = useRouter() const { locales, locale, asPath } = router const setCookie = (name:String, value:String) => { let expires = '' document.cookie = name + '=' + (value || '') + expires + ';'; setAnchorEl(null) } return ( <Fragment> <Button aria-controls="language-menu" aria-haspopup="true" onClick={handleClick}> {`Lang (${locale})`} </Button> <Menu id="language-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose} > {locales?.map(locale=>{ return ( <NextLink key={locale} href={asPath} locale={locale}> <MenuItem onClick={()=>setCookie("NEXT_LOCALE", locale)}>{locale}</MenuItem> </NextLink> ) }) } </Menu> </Fragment> ) }