How to make active Links in Next.JS using styled-components

Viewed 2888

I was making a simple navbar in a side project and faced a problem with active links in Next.JS, in react you could just use react-router-dom that has a Link component with a activeclass atribute, but not in Next.JS (I think)

2 Answers

You can implement this just by using useRouter without using useState (seeing as setState is asynchronous, you would rather use something that doesn't rely on this).

  import { useRouter } from 'next/router';
  ...
  const router = useRouter();

Your Link components would then look like this:

<Link href="/" passHref>
  <LinkText pathName={router.pathname}>Home</LinkText>
</Link>

Finally, your inner component (in my case, it's LinkText) would have this line:

export const LinkText = styled.a`
  color: ${(props) => (props.href === props.pathName ? #728c69 : #fff)};
`;

To make it work I used the UseRouter UseState hooks

const router = useRouter();
const [pathName, setPathName] = useState(router.pathname);

router.pathname is getting whatever /[route] is currently on your url.

const newPathName = () => {
    setPathName(router.pathname);
  };

<Link href="/" passHref>
       <StyledLink onClick={newPathName} pathname={pathName}>
         Home
       </StyledLink>
</Link>

And by using it as a onClick function, it sets the useState to a new route

StyledLink would be the styled component that is going to change colors when clicked

export const StyledLink = styled.a`
  color: ${(props) => (props.href === props.pathname ? "#a37600" : "#eaaa00")};
  text-decoration: none;
  padding-top: 20px;
  font-size: 1.3rem;
  :hover {
    text-decoration: underline;
    color: #a37600;
  }
`;

I basically did this answer because I was searching about this for 30min or so and didn't find anything simple and actually fast enough for a navbar, if there was a similar or simpler answer please link it to me.

Related