I am working with react router dom and trying to give style to active link.
The problem is when I give the active style to the url '/' and when I click another Link, this active style does not leave. Why can it happen?
I mean I click the Link to the url '/' , everything works ok, when I click another Link, the Link with url '/' has active style, but I have already opened another page.
My code is below:
const SideBar = () => {
const getStyle = (isActive:boolean) => {
return isActive ? 'activePage' : 'inactive'
}
return (
<div className="sidebar-overlay">
<ul className="sidebar-content">
<li>
<NavLink
className={({isActive}) => getStyle(isActive)}
to={'/'}>
<Home/>
Главная
</NavLink>
</li>
<li>
<NavLink
className={({isActive}) => getStyle(isActive)}
to={'/sections'}>
<Sections />
Отделы
</NavLink>
</li>
<li>
<NavLink
className={({isActive}) => getStyle(isActive)}
to={'/accounts'}>
<Accounts />
Учетные записи
</NavLink>
</li>
</ul>
</div>
)
};
function Application () {
return (
<div className="container">
<div className="content">
<BrowserRouter>
<Header/>
<SideBar/>
<Routes>
<Route path='/' element={<Main/>}/>
<Route path='/sections' element={<Sections/>}/>
<Route path='/accounts' element={<Accounts/>}/>
</Routes>
</BrowserRouter>
</div>
</div>
)
}
.activePage {
color: white;
border-radius: 10px;
background-color: #007bff;
}
.inactive {
color: black;
}
CodePudding user response:
Try to define a state to represent the currently active page and change the class accordingly:
const SideBar = () => {
const [active, setActive] = useState('')
return (
<div className='sidebar-overlay'>
<ul className='sidebar-content'>
<li>
<NavLink className={active === '' ? 'activePage' : 'inactive'} onClick={() => setActive('')} to={'/'}>
<Home />
Главная
</NavLink>
</li>
<li>
<NavLink
className={active === 'sections' ? 'activePage' : 'inactive'}
onClick={() => setActive('sections')}
to={'/sections'}
>
<Sections />
Отделы
</NavLink>
</li>
<li>
<NavLink
className={active === 'accounts' ? 'activePage' : 'inactive'}
onClick={() => setActive('accounts')}
to={'/accounts'}
>
<Accounts />
Учетные записи
</NavLink>
</li>
</ul>
</div>
);
};