I have a list of compontents I want to share the same state.
I want, at any given time, only the last selected component to have the active state whilst the others to be 'inactive'.
codesandbox link
Thanks.
EDIT:
for SO future proofing of potential dead links:
SidebarList Compontent:
const [active, setActive] = useState(false);
const handleActive = (i) => {
console.log(i);
i.currentTarget.className = active ? "a" : "b";
console.log(i.currentTarget.className);
};
const list = props.items.map((item) => {
return (
<ListItem key={item.id} handleActive={(item) => handleActive(item)}>
{item.text}{" "}
</ListItem>
);
});
return (
<div className="sidebar__list">
<h2>{props.title}</h2>
<ul>{list}</ul>
</div>
);
}
ListItem compontent
function List_item(props) {
return (
<li onClick={props.handleActive}>
<a>
<h2>{props.children}</h2>
</a>
</li>
);
}
export default List_item;
And the App component:
export default function App() {
return (
<div className="App">
<SidebarList
title="About"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
<SidebarList
title="Templates"
items={[
{ id: 1, text: "Item 1 arr" },
{ id: 2, text: "Item 2 arr" }
]}
/>
</div>
);
}
question from:
https://stackoverflow.com/questions/66066346/react-one-state-for-managing-active-flag-on-multiple-compontents 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…