I've a nextjs custom component that adds the locale before the pathname of the page when clicked and adds custom style for the active link..
here is the component
"use client";
import { useLocale } from "next-intl";
import Link from "next/link";
import { usePathname } from "next/navigation";
import React, { useEffect, useState } from "react";
export default function RoutingLink({
children,
href,
className,
activeClass
}: {
children: React.ReactNode;
href: string;
className?: string;
activeClass?: string;
}) {
const currentLocale = useLocale();
const pathname = usePathname();
const [isLinkActive, setIsLinkActive] = useState<boolean>(false);
useEffect(
() => {
if (pathname.slice(1) === href) {
setIsLinkActive(true);
}
() => {
setIsLinkActive(false);
};
},
[pathname]
);
function handleActiveClass() {
if (isLinkActive) {
if (activeClass) {
return activeClass;
} else {
return "text-primaryHover";
}
} else {
return "";
}
}
return (
<Link href={`/${currentLocale}/${href}`} className={`${className} ${handleActiveClass()}`}>
{children}
</Link>
);
}
the problem happened after I created a sidebar tab component *please have a look at the screenshot * , when I click at one link it becomes active and style changes but after I click at another one the previous link still have the active style as well.
I've tried to use useEffect() passing current pathname as dependency library to it, so that whenever the url is changed the active class should be changed and callback function should be called so that active style disappears from previous link.
I think Tailwind won't recall the function even if your component re-renders. Moreover, if there are multiple
RoutingLink
s on the same page, then the old RoutingLink is still mounted when someone clicks on another link - so the callback function onuseEffect
won't get called.Try refactoring like so: