Search code examples
javascriptreactjsbootstrap-modalreact-bootstrap

React Bootstrap: mapping data inside model doesnt show dynamic data in modal


I have a react bootstrap modal where I am mapping my data but the problem is when I click on modals, all the modals display same data, its apparently the last item of the array in all modals. I want to generate modal dynamically and show different data for different modal. Here is some relevant piece of code:


  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
          {availableTeacher ? (
            availableTeacher.teachers.length > 0 ? (
              availableTeacher.teachers.map((data, i) => ( 
                      <Button variant="primary" onClick={handleShow}>
                       Test Modal
                      </Button>

                      <Modal show={show} onHide={handleClose}>
                        <Modal.Header closeButton>
                          <Modal.Title>{data.teacher.name}</Modal.Title>
                        </Modal.Header>
                        <Modal.Body>{data.teacher.name}</Modal.Body>
                        <Modal.Footer>
                          <Button variant="secondary" onClick={handleClose}>
                            Close
                          </Button>
                          <Button variant="primary" onClick={handleClose}>
                            Save Changes
                          </Button>
                        </Modal.Footer>
                      </Modal>
    ```

Solution

  • The issue is, you are creating multiple Modals under loop and all of them are using the same handler in which the state is a boolean variable. So when you click on button it will show all the modals one by one and last one will be on top that why you always seeing the same last modal.

    There are two ways to deal with this issue:

    1. Manage you modal opening state as an array and on every click pass the index and use that index to open that specific modal only.
    2. Create a single modal and pass on the entire data object to it while opening it so that it will show the passed data. By this way only one modal is required and it will show the dynamically passed data. (Recommended)