DaOneRom
DaOneRom

Reputation: 294

Attribute "aria-current='page'" with class='active' not disappearing from first NavLink even after clicking the other links

In my DOM, my elements look like this:

<nav>
   <a aria-current="page" class="item_1 active" href="/">Home</a>
   <a class="item_2" href="/about">About</a>
   <a aria-current="page" class="item_3 active" href="/blog">Blog</a>
   <a class="item_4" href="/contact">Contact</a>
</nav>

Even after clicking the third link, the first link is not changing its attribute and class.

Supposed I have the Menu Component:

import React from 'react'
import { NavLink } from 'react-router-dom'

function Menu(props) {
   const list = [{
      item: 'Home',
      itemLink: '/'
   }, {
      item: 'About',
      itemLink: '/about'
   }, {
      item: 'Blog',
      itemLink: '/blog'
   }, {
      item: 'Contact',
      itemLink: '/contact'
   }]
   const menuItems = list.map((list, index) => {
      return <NavLink className={`item_${index + 1}`} to={`${list.itemLink}`} key={index}> <span>{list.item}</span></NavLink >
   })

   return(
      <nav className="navmenu">{menuItems}</nav>
   )
}

export default Menu

And the Main Component

import React, { Component } from 'react'
import Menu from './Menu'
import Home from './Home'
import About from './About'
import Contact from './Contact'
import Blog from './Blog'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'

class Main extends Component {
   render() {
      return (
         <Router>
            <div>
               <Menu />
               <Switch>
                 <Route exact path='/' component={Home} />
                 <Route path='/about' component={About} />
                 <Route path='/blog' component={Blog} />
                 <Route path='/contact' component={Contact} />
               </Switch>  
            </div>
         </Router>
      )
   }
}

export default Main

How can I make the current link when clicked or hit the back button, will have the attributes (aria-current="page" class="active") set only to the current link and not on the siblings?

Upvotes: 3

Views: 5284

Answers (2)

Cormeistro
Cormeistro

Reputation: 23

I was stumped on this for a couple of days. I just wanted to update this as of React-Router 6.

The exact attribute is now end.

Official documentation states: If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched". This used to be what exact did.

Upvotes: 0

DaOneRom
DaOneRom

Reputation: 294

Based ib @ravibagul91, the solution would be revealed by adding exact prop in NavLink.

const menuItems = list.map((list, index) => {
   return <NavLink className={`item_${index + 1}`} to={`${list.itemLink}`} key={index} exact> <span>{list.item}</span></NavLink >
})

Upvotes: 2

Related Questions