16

Nav works, home link is always active other links are OK. Adding as component, no props.

HTML

 <Menu/>

CSS

.active{
background-color:#ff6a00;
}

JS

import React, { Component } from 'react';
import './menu.css';
import { NavLink } from 'react-router-dom'
export default class TopMenu extends Component {

 render() {
    return (
        <div className="ui container">
            <div className="ui stackable menu">
                <div className="item">
                    <NavLink to='/' >
                        <i aria-hidden="true" className="home  icon" ></i>
                        Home
                     </NavLink>
                </div>
                <div className="item">
                    <NavLink to='/about' >
                        <i aria-hidden="true" className="circle info  icon" > 
                        </i>
                        About
                    </NavLink>
                </div>

                <div className="item" >
                    <NavLink to='/Settings'>
                        <i aria-hidden="true" className="cogs icon red" ></i>
                        Settings
                    </NavLink>
                </div>
            </div>
        </div>
     );
   }
 }

Ideas anyone, why is home always active ?

fuzzybear
  • 2,325
  • 3
  • 23
  • 45

4 Answers4

50

you have to specify the exact prop for your home route '/' because this matches all the other routes, that's why '/' is always active.

 <NavLink to='/' exact={true}>
   <i aria-hidden="true" className="home  icon" ></i>
   Home
 </NavLink>
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22
19

You need to mention end for home route. By default / matches with all it's descendant paths, /about or /settings as well.

<NavLink to="/" end>
  Home
</NavLink>

If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched.

Documentation: https://reactrouter.com/en/6/components/nav-link

Shubham Sarda
  • 539
  • 5
  • 10
5

Make sure you mention end for home ('/') route.

<NavLink to='/' end>
     <i aria-hidden="true" className="home  icon" ></i>
     Home
</NavLink>
Thineshraj S
  • 51
  • 1
  • 2
-1

.active--link{
color:red;
}
<NavLink to="/" activeClassName="active--link"  className="your custom class" > 
    Home 
</NavLink> 
<NavLink to="/classes" activeClassName="active--link" className="your custom class" > 
   Classes 
</NavLink>
asad minhas
  • 147
  • 2
  • 10
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30591165) – xom9ikk Dec 15 '21 at 19:52