Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How to change active nav color in react js while getting data from an array?

I am using array to display nav items in react. I have set classname for all li tags. Now I want when I click on a particular item its color should got changed. I have tried with usestate also but not able to get that. How can I solv this. For more reference, you can check the image.

enter image description here

Check the code below:

import Link from 'next/link'
import Image from 'next/image'
import navbar from '/const/navbar'
import Button from '../button'
import { useState } from 'react'

export default function Navbar() {
   const [activeClass, setActiveClass] = useState();
   return (
      <>
         <nav>
            <input id="nav-toggle" type="checkbox" />
            <div className="logo">
            <Link href="/">
            <Image className=" cursor-pointer h-8 opacity-90" src="/workforwin-logo.png" width={172} height={44} alt="Workforwin Logo" />
            </Link>
            </div>
               <ul className="links">
                  {/* Getting nav items */}
                  {navbar.data.map((items, i) => (
                     <li className='hover:text-indigo-600' key={i}><Link href={items.link}>{items.text}</Link></li>
                  ))}
                  {/* Account Button */}
                  <Button link="" data="Account" type="" />
               </ul>
            <label htmlFor="nav-toggle" className="icon-burger">
               <div className="line"></div>
               <div className="line"></div>
               <div className="line"></div>
            </label>
         </nav>
      </>
   )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

We will assume that the first item in your nav is initially active.

we will set the state to it's default value which is 0

   const [activeClass, setActiveClass] = useState(0);

In the nav items, we will check for each item if the index of that item is equal to the current state, if yes, display it's current color as blue 600.

N.B. i as the 2nd arugment in the map functions are 0 based and represents the index of the current element being processed in the array.

{navbar.data.map((items, i) => (
         <li className={activeClass === i ? "text-blue-600" : "hover:text-indigo-600" } 
          key={i} onClick={() => handleItemClick(i)} >
         <Link href={items.link}>
             {items.text}
         </Link>
         </li>
))}

An onClick handler that changes the state based on the clicked index

const handleItemClick = (idx) => {
// this will trigger a rerender
setActiveClass(idx)
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda