Search code examples
reactjsreact-router-domreact-router-v4

React router dom set active class to the NavLink


I am using React-router-dom for navigation

Routes.js

<Router>
      <Switch>
        <Route path="/" exact component={HomePage} activeClassName="routeActive"/>
        <Route path="/login" exact component={Login} activeClassName="routeActive"/>
        <Route path="/category/veg" exact component={Veg} activeClassName="routeActive"/>
        <Route path="/category/non-veg" exact component={NonVeg} activeClassName="routeActive"/>
      </Switch>
    </Router>

then in my Navbar component i have

<div className="leftNavItems">
          <ul className="navItemsUL">
            <li className="navItemsLI">
              <NavLink to="/" exact className="linkText" activeClassName="routeActive">
                Home
              </NavLink>
            </li>
            <li className="navItemsLI">
              <NavLink to="/login" exact className="linkText" activeClassName="routeActive">
                About us
              </NavLink>
            </li>
            <div className="dropdown">
              {console.log(props)}
              {props.location}
              <span className={` linkText`}>Categories </span>
              <i className="fas fa-caret-down downIcon" />
              <div className="dropdownContent">
                <ul className="dropdownContentUL">
                  <li className="dropdownContentLI">
                    <Link to="/category/:veg" className="dropdownLinkText">
                      Veg
                    </Link>
                  </li>
                  <li className="dropdownContentLI">
                    <Link to="/category/:non-veg" className="dropdownLinkText">
                      Non Veg
                    </Link>
                  </li>
                </ul>
              </div>
            </div>
          </ul>
        </div>

so as u can see i have used "activeClassName" for the Navlink to set className and then change its color if it is active but there is a case where i have a label "Category" which has a dropdown menu that contains for "veg" and "non-veg", so what i want is also need to change the color of "Category" label when the user is in either /category/veg or /caegory/:non-veg as it is Navbar Component console.log(props.location) is undefined over here bacause it is not insise i suppose. Any other way around here >


Solution

  • first, about console.log(props.location) turns to undefined, are you sure you wrapped the component with withRouter? also if it is a function component you can use the hook let location = useLocation()

    second, you can control the class name manually like

       <span className={`${props.location.pathname.split('/').includes('category') ? 'routeActive' : 'linkText' }`}>Categories </span>