Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set isActive on active link in a map loop using NEXTUI navbar?

I’m using the new NEXTUI navbar: https://nextui.org/docs/components/navbar

I want to set isActive property on the active link and there isn’t much help to get from Google so I hope someone here have used it or knows how to do so. I’m using Next.js

A portion of the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Navbar.Content
  enableCursorHighlight
  activeColor="primary"
  hideIn="xs"
  variant="highlight-rounded"
>

  {navigation.map((item, index) => (
    <Navbar.Link key={index} href={item.link}>
      {item.title}
    </Navbar.Link>
  ))}

</Navbar.Content>

EDIT: When I add isActive in the map loop, it effects all. I want to set isActiveon the clicked (active link) one at a time. If I didn’t loop my nav links (which is coming from backend) I could set IsActive property on one but then its just that one that have isActive even if I click on other links.

>Solution :

You have to use a specific condition in your map to check if you are on the correct route.

For example: you can use the next/router and compare it to the link property of the item.

 const { asPath } = useRouter();
.
.
.
//inside return body 
....
 {navigation.map((item, index) => {
    if(asPath === item.link)
   return(<Navbar.Link isActive key={index} href={item.link}>
      {item.title}
    </Navbar.Link>);
  });
  else
 return(<Navbar.Lin key={index} href=. {item.link}>
      {item.title}
    </Navbar.Link>);
  })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading