I developed a simple navbar that has a JSON as data to dynamically construct its links. Visually, I need to persist the navbar with the current active link/route. I tested out two ways:
First implementation:
Menu component:
const ToggleMenuHandler = (e: React.MouseEvent<HTMLElement>) => {
clearMenu();
activateItem(e.currentTarget);
e.stopPropagation();
}
const MenuItems = MenuContent.map(item => {
return (
<NavigationItem key={uuidv4()} {...item} clickHandler={ToggleMenuHandler} />
);
});
Navigation item component:
<ListItem onClick={(event: React.MouseEvent<HTMLElement>) => props.clickHandler(event)}>
<Link href={sub.href}>{sub.name}</Link>
</ListItem>
I'm sure that ToggleMenuHandler function is working properly after debugging it. activateItem is the function responsible for styling an item as active. If I remove the <Link> component from the navigation item, it works just fine. So I figured my menu component was being remounted, which led me to the second implementation.
Second implementation
This one was based on the principle that my menu was being remounted. What I did was to bind the href property of <Link> to the NavigationItem's id. That way, by using router.pathname I could find the item that should be activated, and the code menu component changed to:
const router = useRouter();
useEffect(() => {
activateItem(document.querySelector(`#${router.pathname}`))
}, []);
...and I also removed the ToggleMenuHandler from the menu item component. That way, when the page was redicted I would get its path and, with it, find the list item to activate visually. I also debbug the useEffect hook and it was working properly. However, it was not activated when the Link was clicked.
Question: What exactly is triggered when a NextJS Link component is clicked, and given the context of this question, how can I handle that event?
I don't really know how the Next.js Link component works but I know that it does not need a click event handler.
Also, there should be an <a> tag inside the Link component to work properly as a link according to the docs.
I also have personally experienced if we use another element inside the Link component, it does not work like a link but navigates.