skip to Main Content

I’m learning React Router and is testing some codes. I found that NavLink activeStyle is not working. I’ve followed the instructions on StackOverflow, I still get [object object]. My code:

class Menu extends Component {
    render() {
        return (
            <div>
                <nav>
                    <p><NavLink to="/" activeStyle={{ backgroundColor: "white" }}>Home</NavLink></p>
                    <p><NavLink to="/Contact" activeStyle={{ backgroundColor: "white" }}>Contact</NavLink></p>
                </nav>

                <h1>Begin</h1>
                <Routes>
                    <Route exact path="/" element={<Home />} />
                    <Route exact path="/Contact" element={<Contact />} />
                </Routes >

                <h1>Middle</h1>
                <p><Link to="/">Home</Link></p>
                <p><Link to="/Contact">Contact</Link></p>

                <h1>End</h1>
            </div >
        );
    }
}
export default Menu;

What I see in Inspect is:

enter image description here

Thanks.

2

Answers


  1. react-router-dom no longer supports activeStyle property on NavLink component

    You should use style prop instead:

    Example:

    <NavLink
      to="/"
      style={({ isActive }) =>
        isActive ? { backgroundColor: "white" } : undefined
      }
    >
      Home
    </NavLink>
    
    Login or Signup to reply.
  2. The new way of doing this is via prop style

    <NavLink 
       to="/Contact" 
       style={({isActive}) => isActive ? { backgroundColor: "white" } : undefined}
       className={({isActive}) => isActive ? 'active' : ''}
    >
       Contact
    </NavLink>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search