That my code i don’t know how toi change the state, is i had in the onclickevent : "console.log("clicked" + index) it work and that not work
import React from "react";
interface HeaderListProps {
children: string;
onClickEvent?: () => void;
active: boolean; // Updated assignment
}
class HeaderList extends React.Component<HeaderListProps> {
active: boolean;
children: string;
onClickEvent?: () => void;
constructor(props: HeaderListProps) {
super(props);
this.active = false;
this.children = props.children;
this.onClickEvent = props.onClickEvent; // Updated assignment
}
render() {
return (
<li
className={
"p-1 rounded-xl cursor-pointer transition duration-200 hover:bg-red-300 hover:text-gray-900 hover:scale-105 hover:shadow-xl" +
(this.active ? " bg-red-300" : "")
}
onClick={this.onClickEvent}
>
{this.children}
</li>
);
}
}
export default HeaderList;
import HeaderList from "./headerList";
import { useState } from "react";
interface HeaderProps {
pdp?: string;
navItems: string[];
}
function Header({ pdp = "", navItems }: HeaderProps) {
const [active, setActive] = useState(-1);
return (
<>
<div className="inline-flex flex-row h-auto min-h-16 w-screen items-center bg-gray-800 shadow-lg">
<img src="" alt="logo" className="mx-3 p-auto h-full" />
<h1 className="text-2xl font-bold mx-3 h-full">AccessAutoMoto</h1>
<ul className="list-none inline-flex flex-row flex-wrap gap-3 items-center justify-center m-3 nav-list">
{navItems.map((item, index) => (
<HeaderList
key={index}
onClickEvent={() => setActive(index)}
active={active == index ? true : false}
>
{item}
</HeaderList>
))}
</ul>
<i></i>
<img src={pdp} alt="pdp" className="ml-auto mr-3 cursor-pointer" />
</div>
</>
);
}
export default Header;
Hi,
I try to make a nav bar that allow only one item to be activated (to see on wich page we are),
i try first to change the state in the headerList but i was able to activate mutiple of them and now i try that but it doesn’t work.
3
Answers
I had this little part hand now it refresh but only when the active state of the element return to false, like it false, so not active, i click it pass true but not show as active, i clique multiple time it still not show as active, but if i click on an other it will be show as active, i don't understand why at all
Your issue lies in your class component, you’re just not using the right variables.
Unless you really have to keep it as a class, I’d suggest to convert that to a FC.
If you need a class component then, you need to remove the constructor.
You have a couple of problems here. First, you are using
key={index}
on the loop, which is not a good idea because React uses that to keep track of whether that element belongs to which component. Reference. So you need to change the map in to something like this:Then, you have a class component which is not recommended anymore and you’re not using the
active
prop. It should look something like this: