CodePudding user response:
Try using Route
, Switch
instead of Link
. Link
does not work always. I too had faced some issues while using Link. So then I used Route and Switch instead. Below is an example as to how you can do the same:
class App extends Component {
render() {
return (
<div>
<NavBar />
<div className="containers">
<Switch>
<Route path="/movies/:id" component={MovieForm} />
<Route path="/movies" component={Movies} />
<Route path="/genres/:id" component={GenreForm} />
<Route path="/genres" component={Genres} />
<Route path="/customers/:id" component={CustomerForm} />
<Route path="/customers" component={Customers} />
<Route path="/rentals/:id" component={RentalForm} />
<Route path="/rentals" component={Rentals} />
<Route path="/login" component={LoginForm} />
<Route path="/register" component={RegisterForm} />
<Route path="/error" component={Error} />
<Route path="/not-found" component={NotFound} />
<Route path="/" exact component={Movies} />
<Redirect to="not-found" />
</Switch>
</div>
</div>
);
}
}
CodePudding user response:
The Link
or NavLink
components return an a
HTML tag. So when you are writing the following codes,
<Link to="/home">Home</Link>
It turns out to the following markup on the DOM,
<a href="/home">Home</a>
So the active
class is actually added with the a
tag, not the li
tag.
<a href="/home" class="active">Home</a>
We have to style our CSS considering this approach.
The following updates on your css should work.
.navItem a{
width: 100%;
padding: 1rem 0;
cursor: pointer;
border-right: 4px solid transparent;
transition: all 0.3s ease 0s !important;
list-style: none;
padding-left: 1.3rem;
display: flex;
align-items: center;
}
.navItem a:hover,
.navItem a.active {
border-right: 4px solid red;
}
.navItem a:hover svg,
.navItem a.active svg {
color: red;
}
You don't need to specifically set activeClassName="active"
when you use NavLink
. The active
class is added by default. Check the doc here - https://reactrouter.com/web/api/NavLink/activeclassname-string
CodePudding user response:
you need to replace Link with NavLink . NavLink will add styling attributes to the rendered element when it matches the current URL.
like
<li className={style.navItem} >
<NavLink to='/' activeClassName="active" >
<PersonIcon />
</NavLink>
</li>
<li className={style.navItem}>
<NavLink to='/example1' activeClassName="active" >
<SettingsIcon />
</NavLink>
</li>
<li className={style.navItem}>
<NavLink to='/example2' activeClassName="active" >
<LightModeIcon />
</NavLink>
</li>
here is the documentation link