The Problem
I have a list of detail
tags and I would like to have an opened details
tag close when another one opens.
I am dynamically rendering a list of details
tags
Stack
I am using React and hooks
My attempts
I set the open attribute is set with useState and updated when a details
tag is clicked, but this does not seem to work.
Here is a link to a code sandbox
import { useState } from "react";
const arr = [
{ name: "Jim", age: 22 },
{ name: "Sarah", age: 42 },
{ name: "Don", age: 7 }
];
export default function App() {
const [open, setOpen] = useState(false);
const toggleDetails = (index) => {
setOpen(!open);
};
return (
<ul>
{arr?.map((thing, index) => (
<details key={index} open={open} onClick={() => toggleDetails(index)}>
<summary>{thing.name}</summary>
{thing.age}
</details>
))}
</ul>
);
}