In NextJS, you can apply styling to an active link that is dynamic by using the useRouter
hook provided by the next/router module. The useRouter
hook allows you to access the pathname
property of the router object, which gives you the current URL, and then use it to style the active link.
Here's an example of how you can apply styling to an active link that is dynamic in NextJS:
import { useRouter } from 'next/router';
import Link from 'next/link';
const NavLink = ({ href, children }) => {
const router = useRouter();
const activeLinkStyle = {
color: 'red',
};
const isActive = router.pathname === href;
return (
<Link href={href}>
<a style={isActive ? activeLinkStyle : {}}>{children}</a>
</Link>
);
};
export default NavLink;
In this example, we define a NavLink
component that takes a href
prop and displays a link with the children passed in. Inside the component, we use the useRouter
hook to access the current URL and check if it matches the href
prop. Based on this, we apply the activeLinkStyle
if the link is active, or an empty object if it's not.
We use the Link
component provided by NextJS to create the links, and pass the href
prop to it. We then wrap the link in an <a>
tag and apply the active link styling if the link is active.
Asked: 2023-07-17 04:45:38 +0000
Seen: 11 times
Last updated: Jul 17 '23