Tengo un menú de subtítulos donde me gustaría agregar una clase activa a la página activa. El problema es cuando cambio la configuración regional. Si mi enlace se parece a: my-site/my-page , funciona, pero si mi enlace: my-site/fr/my-page , no funciona. Además, use Storyblok headless CMS.
import { Box, HStack, Link, LinkProps, List, ListItem } from "@chakra-ui/react"; import NextLink from "next/link"; import React from "react"; type SubHeaderLinkProps = { name: string; href: string; isActive: boolean; }; const activeLinkStyles: LinkProps = { color: "orange.400", borderBottom: "1px solid", borderColor: "orange.400", }; const inActiveLinkStyles: LinkProps = { color: "white" }; const SubHeaderLink: React.VFC<SubHeaderLinkProps> = ({ name, href, isActive, }) => ( <ListItem _last={{ base: { pr: 8 }, lg: { pr: 0 } }}> <NextLink href={href} passHref> <Link sx={isActive ? activeLinkStyles : inActiveLinkStyles} py={5} w="min-content" d="block" whiteSpace="nowrap" > {href} </Link> </NextLink> </ListItem> ); Además, se agregó otro archivo de código donde uso el componente SubHeaderLink .
import { SubHeaderLink, SubHeaderLinks, } from "@/components/layout/subHeader/SubHeader"; import { ReactStoryblokComponent, StoryblokLink } from "@/types/storyblok"; import { useRouter } from "next/router"; import { useStoryblokLinkParser } from "storyblok/useStoryblokLinkParser"; type Blok = { subHeaderLinks: { _uid: string; linkName: string; href: StoryblokLink }[]; }; const StoryblokSubHeader: ReactStoryblokComponent<Blok> = ({ blok: { subHeaderLinks }, }) => { const { asPath } = useRouter(); const { getHref } = useStoryblokLinkParser(); return ( <SubHeaderLinks> {subHeaderLinks.map(({ _uid, href, linkName }) => ( <SubHeaderLink key={_uid} href={getHref(href)} name={linkName} isActive={asPath === getHref(href)} /> ))} </SubHeaderLinks> ); }; export default StoryblokSubHeader;La propiedad asPath contiene la ruta actual sin el valor de locale . De la documentación delobjeto del router :
asPath:String- La ruta (incluida la consulta) que se muestra en el navegador sin la configuración regional obasePathlocale.
Suponiendo getHref(href) devuelve una ruta que contiene una configuración regional, también debe compararla con asPath con la configuración regional.
const StoryblokSubHeader: ReactStoryblokComponent<Blok> = ({ blok: { subHeaderLinks } }) => { const { asPath, locale, defaultLocale } = useRouter(); // Get the current locale const { getHref } = useStoryblokLinkParser(); const getCurrentPath = () => { if (locale === defaultLocale) return asPath return `/${locale}${asPath}` } return ( <SubHeaderLinks> {subHeaderLinks.map(({ _uid, href, linkName }) => ( <SubHeaderLink key={_uid} href={getHref(href)} name={linkName} isActive={getCurrentPath() === getHref(href)} /> ))} </SubHeaderLinks> ); };