Ask Your Question
2

How can styling be applied to an active link that is dynamic in NextJS?

asked 2023-07-17 04:45:38 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-17 04:58:02 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-17 04:45:38 +0000

Seen: 11 times

Last updated: Jul 17 '23