-1

Is there any way to set active state in active attribute instead of activeClassName on React Router NavLink? For a specific reason, it needs to be in the active state. There is this isActive function in NavLink that I think might be useful to achieve what I need. But so far I have no result. I was thinking of something like below but it does not work.

What I have tried:

const abc = (match, location) => {
  return match;
}
<NavLink to="/faq" isActive={abc} active={props.isActive ? "true" : null}>
  FAQs
</NavLink>
Ela Yudhanira
  • 66
  • 1
  • 10

1 Answers1

0

It is not very clear what you're trying to achieve, but this is my best guess: you want some way to know if the NavLink is active or not.

By default, the NavLink is active if it matches the URL that you provided in to. You can do this check manually using the matchPath method provided by React Router:

import { matchPath } from "react-router";

const toUrl = '/faq';

const isActive = matchPath(toURL, {
  path: this.props.match.path,
});

<NavLink to={toUrl}>
  FAQs
</NavLink>

This will check that the current path matches "/faq". Now you have a variable isActive that is true when the NavLink is active, and false when inactive. You can the use that for whatever you want.

I'm not sure what you were trying to accomplish with the active prop, but that is not a valid prop for NavLink.

Raicuparta
  • 2,037
  • 15
  • 22
  • How do I get the value in active attribute? I tried `active= {isActive ? "true" : null}` but it always return true, even though it's not in a matched location – Ela Yudhanira Sep 25 '19 at 11:39
  • I changed my answer. See if it helps now. You question in general is very vague an you need to work on being more clear, it's very hard to help you this way. – Raicuparta Sep 25 '19 at 11:50
  • Thanks for your input, I have updated my question and tried my best to make it clear. I know active attribute is not part of NavLink, I'm just curious if there's a way to add active state in attribute instead of className. Or is there a way around this. Because in HTML NavLink will be rendered as an `a` element, so I want the active attribute added on the `a` element. – Ela Yudhanira Sep 25 '19 at 12:08
  • Your question still doesn't seem to make much sense, and I still have no idea what you were trying to achieve with that code. What is the `abc` methodsupposed to do? What is `active={props.isActive ? "true" : null}` supposed to be for? What do you mean by "set active state"? – Raicuparta Sep 25 '19 at 19:46