I have a mapped array
const numbers = [
{id : 1, number : 1},
{id : 2, number : 2},
{id : 3, number : 3},
{id : 4, number : 4},
]
It's not a real one but it is similar to the array which is I have from the api like
// state
const [open, setOpen] = useState(false);
numbers.map((number) =>
<Button
key={number.toString()}
onClick={() => setOpen(!open)}
aria-controls="example-collapse-text"
aria-expanded={open}
>
click
</Button>
and on click it returns
<div style={{minHeight: '150px'}}>
<Collapse in={open} dimension="width">
<div id="example-collapse-text">
<Card body style={{width: '400px'}}>
Some text
</Card>
</div>
</Collapse>
</div>
But problem is it's rendering the Collapse on each click on all the elements on the array, How can I make it unique to each element to work around.
CodePudding user response:
you are setting one open
state for all of collapse
so by clicking one of the buttons all of the collapse components appear. you have to implement an open state on each collapse itself like so:
import { Button, Card, Collapse } from "@mui/material";
import { useState } from "react";
function Test() {
let numbers = [1, 2, 3];
return numbers.map((number) => <MyCollapse number={number} />);
}
function MyCollapse({ number }) {
const [open, setOpen] = useState(false);
return (
<>
<Button
key={number.toString()}
onClick={() => setOpen(!open)}
aria-controls="example-collapse-text"
aria-expanded={open}
>
click{" "}
</Button>
<div style={{ minHeight: "150px" }}>
<Collapse in={open} dimension="width">
<div id="example-collapse-text">
<Card body style={{ width: "400px" }}>
Some text
</Card>
</div>
</Collapse>
</div>
</>
);
}