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.
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>
</>
)
}
CodePudding user response:
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)
}