I have a quiestion for everyone here.
I am using react to make a portfolio page, and I am curious about one thing.
I just want to add a class to anchor tag when the tag is clicked, and i want to remove the class when the other anchor tag(of course this newly clicked one is gonna have the class) is clicked.
I just want to know about it and want to adopt it to improve my coding skills.
Hope lots of people here can help me.
The one below is my jsx code.
export function HeaderMenu() {
const [menuList, setMenuList] = useState([]);
useEffect(() => {
fetch("data/menu.json")
.then((res) => res.json())
.then((result) => setMenuList(result))
.catch((error) => console.log(error));
}, []);
return (
<div>
<nav>
<ul className="header__menu">
{menuList.map((menu, index) => (
<li key={index}>
<Menu href={menu.href} name={menu.name} />
</li>
))}
</ul>
</nav>
<button
id="menu_toggle"
className="header__toggle"
aria-label="navigation menu toggle"
>
<i className="fa-solid fa-bars"></i>
</button>
</div>
);
}
The one below is the component of the .
import React from "react";
export default function Menu({ href, name }) {
return (
<a className="header__menu__item" href={href}>
{name}
</a>
);
}
I tried lots of things in Internet but i couldn’t find the right answer.
Thank you!
2
Answers
I usually use some logic like using
useState
oruseContext
for multiple componentHope this help :>
You can manage the state of the active anchor tag within the HeaderMenu component.
Then for the Menu Component:
the currently active menu item.
updating the activeMenuIndex state.
apply the "active" class to the anchor tag.
the click event.