简体   繁体   中英

React activeClassName property of NavLink not working

I've been trying to use the activeClassName property of NavLink for applying a certain color and background to the links/anchors. But the changes weren't displayed upon clicking. I'm attaching the js and CSS snippets below

 import React from 'react'; import { NavLink } from 'react-router-dom'; import './navbar.css'; const Navbar = () => { return ( <div className='navbar'> <div className='navbar__left'> <NavLink to='/'>Clubhub</NavLink> </div> <div className='navbar__right'> <NavLink activeClassName='active_link' to='/'> Home </NavLink> <NavLink activeClassName='active_link' to='/membership'> Membership </NavLink> <NavLink activeClassName='active_link' to='/booking'> Booking </NavLink> <NavLink activeClassName='active_link' to='/profile'> Profile </NavLink> </div> </div> ); }; export default Navbar;

 .active_link { background-color: #224461; color: white; }
Please help me figure out the issue. Thanks!

As per react-router docs ,

In React Router v6, activeClassName will be removed and you should use the function className to apply classnames to either active or inactive NavLink components.

Here is an updated version:-

import React from "react";
import { NavLink, BrowserRouter as Router } from "react-router-dom";
import "./navbar.css";

const classNameFunc = ({ isActive }) => (isActive ? "active_link" : "");

const App = () => {
  return (
    <Router>
      <div className="navbar">
        <div className="navbar__left">
          <NavLink to="/">Clubhub</NavLink>
        </div>

        <div className="navbar__right">
          <NavLink className={classNameFunc} to="/">
            Home
          </NavLink>
          <NavLink className={classNameFunc} to="/membership">
            Membership
          </NavLink>
          <NavLink className={classNameFunc} to="/booking">
            Booking
          </NavLink>
          <NavLink className={classNameFunc} to="/profile">
            Profile
          </NavLink>
        </div>
      </div>
    </Router>
  );
};

export default App;

The above code in action:-

编辑 React-rourt-dom-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