Sedrick Nyanyiwa
Sedrick Nyanyiwa

Reputation: 105

How to pass value to modal using React.js?

I have a table that returns data after a .data.map().. as shown below:

{this.state.data.map((item, i) => { 
   return (div>
              <tr>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.symbol}</td>

And a <td> in the same <table> and <tr> above that displays my modal with the below code:

<td>
    <div>
        <a className="btn" href="#open-modal" title="More Details">👁</a>
        <div id="open-modal" className="modal-window">
        <div>
          <a href={url} title="Close" className="modal-close">❌</a>
          <div>Update Details</div>
            <label>{item.id}</label> //WHERE I WANT TO DISPLAY MY ID
        </div><a href={url}></a></div>
    </div>
</td>

Now when I want to display the item.id of each particular row after opening the modal, it returns the item.id of only 1 item in the array and not the actual item.id.

So the item.id in <td> is different from the item.id in the modal. It keeps returning the same item.id for every row I click on. How can I have these 2 have the same value?

Upvotes: 0

Views: 554

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

The modal only reference to your last id at the time you rendered it

I would suggest you have a state to store your id and render it when you open your modal.

Something like:

const [selectedId, setSelectedId] = useState();

<td>
    <div>
        <a
          className="btn"
          onClick={() => setSelectedId(item.id)}
          href="#open-modal" title="More Details"
        >👁</a>
        <div id="open-modal" className="modal-window">
        <div>
          <a href={url} title="Close" className="modal-close">❌</a>
          <div>Update Details</div>
            <label>{selectedId}</label>
        </div><a href={url}></a></div>
    </div>
</td>

The 👁 looks scary though.

Upvotes: 1

Related Questions