React NavLink: isActive function throws 'string is not assignable to type string | undefined'

Viewed 113

I defined NavLinks for styling an active link.

For instance I tried several approaches of this kind:

<NavLink to="contact" className={({ isActive }) => (isActive ? 'nav-links-active' : 'nav-links')}>
      Contact
</NavLink>

This doesn't work and the IDE returns:

Type function({isActive: any}): string | string is not assignable to type string | undefined   Type function({isActive: any}): string | string is not assignable to type string

Do I have to define isActive somewhere? What am I doing wrong?

2 Answers

className does not accept callback functions. If isActive a variable or a state you can simply do this:

<NavLink to="contact" className={isActive ? 'nav-links-active' : 'nav-links'}>
      Contact
</NavLink>

Use activeClassName instead. You can simply do this:

<NavLink to="contact" activeClassName='nav-links-active' className='nav-links'>
      Contact
</NavLink>

But it works in react-router-dom v5. It does not exist in v6 anymore. For further details see documentation

Related