简体   繁体   中英

Add Edit Button to react-table that opens up modal to edit row attributes that overwrites table row with edits

I am trying to add an Edit button to each row of my react-table that opens up a Modal form that allows the user to save edits to different attributes of the row (some of which may or may not be displayed in the table). Upon clicking "save" in the Modal, a post request to the API is made and the row in the react-table is updated with the response.

I have attempted to add an onClick that calls a handleEdit function, but all that is passed to handleEdit is undefined? How can I access the row attributes (even the ones not being displayed in the table) and overwrite them with a new value?

Header: 'Action',
            accessor: 'action',
            Cell: row => (
            <div>
               <button onClick={row => handleEdit(row.original)}>Edit</button>
            </div>
            ),
function handleEdit(row) {
    console.log(row);
    // display modal
    // say user types in modal new firstName
    // post request

    // set row.firstName = newFirstName
 
  }

Here is the sandbox: https://codesandbox.io/s/elated-currying-scvxk?fontsize=14&hidenavigation=1&theme=dark

The reason you are getting undefined is because you have overridden row. by default, when a button is clicked, it calls the onClick() method and passes an Event as the first parameter to the function. your onClick function calls this parameter 'row', so when you reference row, you are referencing the event parameter not the actual row;

You can try changing the parameter name so that 'row' still references the original variable;

Also, After looking at your sandbox code, it turns out that the 'row' variable doesn't have any 'original' property, but rather it has another 'row' property which has the 'original' property:

Header: 'Action',
            accessor: 'action',
            Cell: row => (
            <div>
               <button onClick={e=> handleEdit(row.row.original)}>Edit</button>
            </div>
            ),

I fixed it here. https://codesandbox.io/s/cocky-poincare-b24mt

Cause accessor: 'action' will map to the data item and it doesn't find it there then it return undefined. Then in your initialization data stage I add one more property for action. Your Cell function have a bit wrong syntax too. I updated it in my sandbox. You can check it

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