简体   繁体   中英

Navlink from react-router-dom Home always active

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?

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>

 .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>

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

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

<NavLink to='/' end>
     <i aria-hidden="true" className="home  icon" ></i>
     Home
</NavLink>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM