Sometimes, we want to set the active class name for wrapper element of React Router links.
In this article, we’ll look at how to set the active class name for wrapper element of React Router links.
Set activeClassName for Wrapper Element of Link or IndexLink in React Router
We can create a wrapper element for a link by creating a component.
The activeClassName
value can be passed in from the props.
For instance, we can write:
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
class NavHeaderextends Component {
render (){
return (
<header>
<ul>
<li>
<NavLink activeClassName="active" exact to="/">home</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">About</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/courses">profile</NavLink>
</li>
</ul>
</header>
);
}
}
We use the NavLink
component to create the navigation links.
activeClassName
is a string that we can set to the class that’s applied when the link is active.
to
is the path that the link goes to.
Conclusion
We can create a wrapper element for a link by creating a component.
The activeClassName
value can be passed in from the props.