Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router V6 NavLink doesn't show active

Trying to replace some old methods with NavLink and react-router but my code doesn't seem to work

   return (
      <div className='Selection-container'>
      <div className="Selections">
      <NavLink to="/best">
       <button  className='Best' value='best' onClick={handleSelection}>Best</button>
       </NavLink>
      <NavLink to="/hot" >
       <button  className='Hot' value='top' onClick={handleSelection}>Hot</button>
       </NavLink>
      <NavLink to="/new" >
       <button   className='New' value='new' onClick={handleSelection}>New</button>
       </NavLink>
      </div>
        {loading && <div className='Loading-main' ><img src={loadingImg} alt='loading' className='Main-loading' /></div>}
     
      <Routes>
        <Route path='/best' element={<PostMain />} />
        <Route path='/hot' element={<PostMain />} />
        <Route path='/new'  element={<PostMain />}/>
      </Routes>
      </div>
  );
}

I'm trying to render different kind of post inside the buttons seem to work they change the content in the page the change the route in the browser just the "active" button is not active when i'm on Best-Hot or New pages (at the end i wanna display active:inactive images in css as background but for now i would settle with anything that shows the current active page ).

like image 509
Csaba burján Avatar asked Oct 20 '25 17:10

Csaba burján


2 Answers

As i understand the problem, here's an example of what you need

<NavLink style={({ isActive }) => isActive ? {backgroundImage:'yourimg'} : {}} 
        ...
</NavLink>

You can use className insted of style

<NavLink className={({ isActive }) => isActive ? 'activeBtn' : ''} 
        ...
</NavLink>
like image 190
ZomitaKa Avatar answered Oct 23 '25 06:10

ZomitaKa


yes in v6 a few have changed, "end" works as "exact" and "strict" before

import { NavLink } from 'react-router-dom'
<li>
  <NavLink end to="/">
    HOME
  </NavLink>
</li>

you can style the active link with the selector:

[aria-current="page"] {
    background-color: purple;
}
like image 41
codmitu Avatar answered Oct 23 '25 05:10

codmitu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!