简体   繁体   中英

React - the right way to show data using multiple react-bootstrap modal

In an effort to learn React.js I created a simple app to display the personal data of all employees, using react-bootstrap . But there was a problem with Modal and I haven't found a solution. The problem is the data that appears for all Modal is the last employee data, in this case employee-03 .

Take a peek at the code here (not the full code), https://codesandbox.io/s/peaceful-wave-cjdo3

Based on this article, React-Bootstrap Multiple Modal I suspect it seems that all Modal uses the same ID. What I'm confused about is how to set a different ID for each Modal if employee data will later be retrieved from a JSON file?

Thanks.

Regards, Erol.

You are using the same state to toggle all of the modals. If you play with the developer tools from React, you can see that every modal has it's corresponding data. I would create an array of booleans in the state or a string with an id :

  const [modalId, setModalId] = React.useState("");
  const handleClose = () => setModalId("");

  return (
    <Row className="App">
      {data.map((pax, i) => (
        <Col xs={12} md={4} key={pax.Uniquename}>
          <Card>
            <Card.Body>
              <Card.Title as="h4">{pax.Uniquename}</Card.Title>
              <Button type="button" onClick={() => setModalId(`modal${i}`)}>
                Open Modal
              </Button>
            </Card.Body>
            <Modal
              show={modalId === `modal${i}`}
              onHide={handleClose}
              aria-labelledby={`${pax.Uniquename}ModalLabel`}
              centered
            >
              <Modal.Header id={`${pax.Uniquename}ModalLabel`} closeButton>
                {pax.Uniquename}
              </Modal.Header>
              <Modal.Body>Full Name: {pax.Name}</Modal.Body>
            </Modal>
          </Card>
        </Col>
      ))}
    </Row>
  );

PS: It's just an example, you can re think your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM