Problem:
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.
Case:
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>
</>
);
}
}
Question:
Is there any method to achieve this goal in a react class component?
Expected answer:
- Reference to a working example
- Code snippet
- Explanation why this would not work
- Alternative solution
Thank you in advance!
Thanks to @genius fox dev, this solution did work for me!
Solution:
{/* 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>