question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

New example: active route hook

See original GitHub issue

Feature request

Is your feature request related to a problem? Please describe.

The current <Link> component from next/link does not include an active prop when a link is clicked.

There is currently an example of how to implement active-class-name which allows styling of an active link by passing a className (and then styling it via style jsx). However, this might not work for users who are using UI frameworks such as bootstrap, or alternative CSS-in-JSS solutions like styled-components.

Describe the solution you’d like

I’ve adapted the ActiveLink.js file from the active-class-name` example to pass an active prop instead of a className. Here’s the code:

# /components/Link.js

import { withRouter } from 'next/router';
import Link from 'next/link';
import React, { Children } from 'react';

const ActiveLink = ({ router, children, ...props }) => {
  const child = Children.only(children);

  let active = child.props.active || null;
  if (router.pathname === props.href) {
    active = true;
  }

  delete props.active;

  return <Link {...props}>{React.cloneElement(child, { active })}</Link>;
};

export default withRouter(ActiveLink);

Then, when importing this component, e.g. in Nav.js, there is no need to include <Link activeClassName="active" href="/">. Instead, you can simply use <Link href="/"> and the active prop is automatically passed to whichever Link the user clicks on (e.g. <Link active href="/">

# /components/Nav.js

import Link from './Link'
import styled from 'styled-components'

const StyledLink = styled(Link)`
  text-decoration: none;
  padding: 10px;
  display: block;
  ${props =>
    props.active &&
    'background-color: #d9e9fb; color: #444; font-weight: 500;'}
`

export default () => (
  <nav>
    <ul>
      <li>
        <StyledLink href='/'>
          <a className='nav-link home-link'>Home</a>
        </StyledLink>
      </li>
      <li>
        <StyledLink href='/about'>
          <a className='nav-link'>About</a>
        </StyledLink>
      </li>
    </ul>
  </nav>
)

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:9
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

6reactions
shobhit-jaincommented, Aug 16, 2020

i did something like this with typescript and tailwind css and it works fine :

import { useRouter } from 'next/router'
import Link from 'next/link'

type Props = {
  href: string
  linkName: string
  activeClassName?: string
} & typeof defaultProps

const defaultProps = {
  activeClassName: 'text-green font-600',
}

export const NavLink = ({ href, linkName, activeClassName }: Props) => {
  const router = useRouter()

  return (
    <Link href={href}>
      <a className={router.pathname === href ? activeClassName : null}>
        {linkName}
      </a>
    </Link>
  )
}

NavLink.defaultProps = defaultProps
3reactions
elliottjrocommented, Jun 5, 2019
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using Hooks with React Router - LogRocket Blog
In this tutorial, you can learn how to use Hooks with React Router and minimize code lines in a component.
Read more >
useHistory hook - React Router: Declarative Routing for React.js
The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a...
Read more >
React-Router Hooks - GeeksforGeeks
We will discuss all the hooks in details with proper examples: 1. useHistory: This is one of the most popular hooks provided by...
Read more >
Active NavLink Classes with React Router - Ultimate Courses
Programmatically navigate with React Router (and Hooks). How to programmatically navigate with React Router v6 and the new useNavigate hook.
Read more >
The Hooks of React Router - CSS-Tricks
React Router 5 embraces the power of hooks and has introduced four different hooks to help with routing. You will find this article...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found