'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 ).
Solution 1:[1]
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>
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ZomitaKa |
| Solution 2 |
