0

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.

Functional way

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>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Samuel Ferdary
  • 315
  • 2
  • 11

1 Answers1

1

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

genius dev
  • 143
  • 7