DaveCat
DaveCat

Reputation: 813

How do I get table Data from a row onChange of dropdown menu when an event is fired in React?

Here's the workflow:

  1. User accesses my react component that renders a table
  2. One of the elements within each row has a dropdown menu
  3. User changes the value of the dropdown (flavor)
  4. An event is fired that submits this data to our APIService

Here's the problem:

When I consume the drop down change event that's fired after selection, it contains the new flavor. However, it doesn't tell me the record from the table that changed (which I need). I need this to update the record in the backend.

Here's the code:

...
<tbody>
   {data.map((row, key) => (
       <tr key={key}
           <td>
               <select onChange={handleStatusChange} className="form-select">
               <option value="value">{myObject[key].flavor}</option>
               <option value="chocolate">chocolate</option>
               <option value="strawberry">strawberry</option>
               <option value="Vanilla">Vanilla</option>
           </td>
 ...

The weird thing is that I can obviously identify row and row id from "row/key" within the table. However, whenever I consume the event, none of that data is there:

const handleStatusChange = (event, id:any) => {

    backendService.setNewFlavor(data).then(response) => {
      ...this needs row.flavorID
 
    }
}

What I've tried

I don't need you to spoonfeed me or solve the problem for me, I just need an example of someone doing something like this.

Bonus points if we can make this change dynamically render to the page without refreshing it.

Upvotes: 0

Views: 866

Answers (1)

David
David

Reputation: 218877

If key (which is just the array index) really is the "unique identifier" you need then you can simply pass it to the handler function:

onChange={e => handleStatusChange(e, key)}

Then the function signature you have would receive those two arguments:

const handleStatusChange = (event, id:any) => {

Alternatively, if row itself contains an identifier you can use, you can pass that to the handler:

onChange={e => handleStatusChange(e, row.id)}

Or pass the entire row itself:

onChange={e => handleStatusChange(e, row)}

Basically, you can pass whatever argument(s) you like to handleStatusChange.

Upvotes: 1

Related Questions