[Solved] react-router-dom Error: <NavLink>activeClassName

Requirement: click the corresponding button to highlight

Error code:

Demo is the style class name corresponding to the highlight

<NavLink activeClassName="demo" className="list-group-item" to="/about">About</NavLink>
<NavLink activeClassName="demo" className="list-group-item" to="/home">Home</NavLink>

Error message:

It is said that react does not recognize the activeclassname attribute of the small hump writing method. It is recommended to change it to lowercase. After changing it to lowercase activeclassname, no error will be reported, but the style does not take effect.

Later, I found out that my react router DOM version is the latest version: 6.0 2:

In the new version, the active classname attribute is no longer used to highlight naclink. Instead, it is implemented directly in the classname as a callback function.

Change to the following code:

<NavLink className={({isActive}) => 'list-group-item' + (isActive ?' demo' : '')} to="/about">About</NavLink> 
<NavLink className={({isActive}) => 'list-group-item' + (isActive ?' demo' : '')} to="/home">Home</NavLink>

Note: a space should be added before “demo”. Otherwise, when clicking the button to trigger the active state, it will return to “list group itemdemo” (string splicing, if no space is added, the front and rear class names will be connected together), resulting in the ineffective CSS style.

Read More: