React router hooks can be used in function components to retrieve the current route.
However, I can not find any reference for the class component.
I have a navigation menu and I want to keep track of the current route to highlight it in the front end by switching the css classes according to the current state.
Navigation excerpt:
import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
...
export default class Nav extends Component {
...
render = (): JSX.Element => {
return (
<>
{/* Current: "border-green-500 text-gray-900" */}
{/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */}
<Link to="/"
className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
>
Home
</Link>
</>
);
}
}
Is there any method to achieve this goal in a react class component?
Thank you in advance!
Thanks to @genius fox dev, this solution did work for me!
{/* Current: "border-green-500 text-gray-900" */}
{/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */}
<NavLink // from 'react-router-dom'
to="/"
className={
( {isActive} ) => ( isActive
? 'border-green-500 text-gray-900'
: 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
).concat( ' inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium' )
}
>
Home
</NavLink>
You can use NavLink is supported at react-router-rom v6.0.
First, change the link to navlink, and then show carefully below code.
<NavLink
style={({ isActive }) => {
return {
display: "block",
margin: "1rem 0",
color: isActive ? "red" : ""
};
}}
to={`/invoices/${invoice.number}`}
key={invoice.number}
>
{invoice.name}
</NavLink>
please, refer to url. https://reactrouter.com/docs/en/v6/getting-started/tutorial#active-links