[Accordion] Toggling all Accordion.Items #1938
-
Hello 👋 , I was wondering if there's an easy way to toggle all function ToggleAllAccordions() {
const [isClosed, setClosed] = useState(false);
return (
<>
<button onClick={() => setClosed(!isClosed)}>Toggle all accordions</button>
<Accordion.Root openAll={isClosed} type="multiple" collapsible>
<Accordion.Item>…</Accordion.Item>
<Accordion.Item>…</Accordion.Item>
</Accordion.Root>
<>
)
} Or if there's a way to expose all the Would love to hear back with your feedback! Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
@binhxn, the way to do this is to use the controlled API. For example, something like: const items = [
{ value: 'one', title: '…', content: <>…</> },
{ value: 'two', title: '…', content: <>…</> },
{ value: 'three', title: '…', content: <>…</> },
];
const allValues = items.map(item => item.value);
function ToggleAllAccordions() {
const [value, setValue] = useState([]);
return (
<>
<button onClick={() => setValue(prev => prev.length > 0 ? [] : allValues}>Toggle all accordions</button>
<Accordion.Root type="multiple" collapsible value={openItems} onValueChange={setOpenItems}>
{items.map(item => <Accordion.Item value={item.value}>…</Accordion.Item>)}
</Accordion.Root>
<>
)
} Depending on what you want the UX to be when "toggling" all items (if only some are currently open) you may want to change this bit: setValue(prev => prev.length > 0 ? [] : allValues At the moment this is saying, "if there are any items open and you click the button, close them all, otherwise open them all". Hope this makes sense ✌️ |
Beta Was this translation helpful? Give feedback.
@binhxn, the way to do this is to use the controlled API.
For example, something like: