Search code examples
reactjsnext.jsstyled-components

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


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)


Solution

  • 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.