This question has been asked many times and I looked and tried many solutions.
I'm using NavLink from react-router-dom and I want to toggle the className active to mark the link clicked here is the code:
import React from 'react'
import styles from './NavBar.module.css'
import logo from '../assets/logos/icon-left-font-monochrome-white.svg'
import { NavLink } from 'react-router-dom'
export default function NavBar() {
return (
<div className={styles.nav_contrainer}>
<img className={styles.img} src={logo} alt='logo groupomania avec typo blanc' />
<nav className={styles.nav}>
<NavLink to='/home' exact='true' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
<li>Home</li>
</NavLink>
<NavLink to='/articlebuilder' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
<li>Écrire un article</li>
</NavLink>
<NavLink to='/profile' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
<li>Profile</li>
</NavLink>
</nav>
</div>
)
}
This code has a solution from an other post, how ever it's not working for me...
I tried the exact='true' in all links but it still doesn't work.
Here is the code where the path are linked
<div className='App'>
<Routes>
<Route path='/' exact={true} element={<HomePage />} />
<Route path='/landingpage' exact={true} element={<LandingPage />} />
<Route path='/home' exact={true} element={<HomePage />} />
<Route path='/profile' exact={true} element={<Profile />} />
<Route path='/articlebuilder' exact={true} element={<ArticleBuilder />} />
<Route path='/signup' exact={true} element={<Signup />} />
<Route path='/signin' exact={true} element={<Signin />} />
</Routes>
</div>
this is the css file:
.nav_contrainer {
background-color: #ffac99;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0em 0em 0em 1em;
}
nav {
display: flex;
position: sticky;
}
nav a {
list-style: none;
font-size: 1.6em;
color: white;
transition: all ease-in-out 350ms;
padding: 10px;
}
nav a:hover {
color: #870e07;
cursor: pointer;
}
.nav_contrainer img {
width: 15%;
height: 15%;
}
.active {
color: #870e07;
font-weight: bold;
}
Have I missed something?
It seems your class needs to be the active class from the NavBar CSS module.
function NavBar() {
return (
<div className={styles.nav_contrainer}>
<img className={styles.img} src={logo} alt='logo groupomania avec typo blanc' />
<nav className={styles.nav}>
<NavLink
to="/home"
className={(navData) => (navData.isActive ? styles.active : "none")}
style={{ textDecoration: "none" }}
>
<li>Home</li>
</NavLink>
<NavLink
to="/articlebuilder"
className={(navData) => (navData.isActive ? styles.active : "none")}
style={{ textDecoration: "none" }}
>
<li>Écrire un article</li>
</NavLink>
<NavLink
to="/profile"
className={(navData) => (navData.isActive ? styles.active : "none")}
style={{ textDecoration: "none" }}
>
<li>Profile</li>
</NavLink>
</nav>
</div>
);
}