Reputation: 349
I want to add active class which router is active in react. I start learning react so i need some help in this. I need to add the class in the li element not on the Link element.
<ul className="list-unstyled">
<li className={RouteHelper("/")}> <Link to="/"> <FaHome /> Home </Link> </li>
<li className={RouteHelper("/tables")}><Link to="tables"> <FaTable />Tables </Link></li>
</ul>
Here is the function which is getting active class
const RouteHelper = (url) => {
return window.location.pathname === url ? "active" : null;
}
export default RouteHelper;
Upvotes: 1
Views: 2386
Reputation: 1
//At first you can create a css style.it is applied in the react router v6.
const navLinkStyles = ({isActive})=>{
return{
color:isActive?'lightgreen':'white',
fontWeight:isActive?'bold': 'normal'}}
//Then apply this css in link
<NavLink as={Link} to='/manage' style={navLinkStyles} className="hidden md:block mx-5 text-gray-300 hover:text-white" >Manage Items</NavLink>
Upvotes: 0
Reputation: 9713
I think you would need to create a CustomLink. Here is the code from the react-router docs.
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const CustomLinkExample = () => {
return (
<Router>
<div>
<ul>
<ListItemLink activeOnlyWhenExact={true} to="/">
<FaHome /> Home
</ListItemLink>
<ListItemLink activeOnlyWhenExact={true} to="/tables" label="Tables">
<FaTable />
Tables
</ListItemLink>
</ul>
<hr />
<Switch>
<Route path="/" component={Home} exact />
<Route path="/tables" component={Tables} exact />
</Switch>
</div>
</Router>
);
};
const ListItemLink = ({ to, activeOnlyWhenExact, children }) => {
return (
<Route
path={to}
exact={activeOnlyWhenExact}
children={({ match }) => (
<li className={match ? 'active' : ''}>
<Link to={to}>{children}</Link>
</li>
)}
/>
);
};
const Home = () => {
return (
<div>
<h2>Home</h2>
</div>
);
};
const Tables = () => {
return (
<div>
<h2>About</h2>
</div>
);
};
Here is the working code: https://codesandbox.io/s/reactrouter-62rye
Upvotes: 1