Why is my modal only taking the first prop passed to it? (Using React and Bootstrap)

Viewed 16

Hello :) I'm using Bootstrap to make an offcanvas component that can render a modal for each item in an array passed to it. However, when clicking open my modals, they each display omly the first items props. Why? And, how can I fix it? I recreated it here in codesandbox codesandbox recreation If i can improve my question let me know in a kind way, please.

1 Answers

The way you have done is not the correct way of building Modal in React . However just to give you clarity about the mistake you have done:

The prop letter is passed correctly. The problem is the way you're calling the modal.

If you see your code in Example.js , you have used data-bs-target="#exampleModal". And id="exampleModal" for the modal to show up. So all the handlers are pointing to exampleModal id . Hence After you click on the buttons only the first modal shows up.

To solve this , you need to assign the data-bs-target and id dynamically. Something like below :

  <button
        type="button"
        class="btn btn-primary"
        data-bs-toggle="modal"
        data-bs-target={`#exampleModal${props.letter}`}
      >
        click to view prop
      </button>

and then in Modal set id as :

<div
        class="modal fade"
        id={`exampleModal${props.letter}`}
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >

It should work as expected.

here is the working example : Demo

Related