Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
How to configure Collapse toggle different on each element in the mapped array

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
    </>
  );
}


about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!