Search code examples
reactjsreact-router-dom

How can NavLink assign active separate with URL query string?


I'm working on a list of NavLink with different query string

  <ul>
    <li>
      <NavLink
        to="?type=all"
        end>
        all
      </NavLink>
    </li>
    <li>
      <NavLink
        to="?type=asdf"
        end>
        asdf
      </NavLink>
    </li>
    <li>
      <NavLink
        to="?type=1234"
        end>
        1234
      </NavLink>
    </li>
  </ul>

And I want to add some css on the active link, but I found that they all acitve all the same time because of they have same URL.

Differ NavLink Active for Same Link but Muliples Query Paramas Id

I found a similiar question here and try the solution of useLocation(), but it doesn't work. So I log the value of props.to and location.pathname.

props.to: ?type=aaaaa
location.pathname: /console/products

The pathname just return the URL so it always return FALSE with compare to props.to, then I can't assign the active css class to the element.

Is it something changed in react-router-dom v6 or I make it wrong?


Solution

  • const {search} = useLocation()
    const type = new URLSearchParams(search).get('type')
    
    <NavLink
        to="?type=1234"
        // this is react-router-dom v6 way
        className={({isActive}) => (isActive && type === '1234') ? 'active' : ''}
        end
    >
        1234
      </NavLink>