Get Properties of each row in react table upon button click

Viewed 49

I have a react table with two columns like so:

{
      Header: 'Toe ID',
      id: 'toe_id',
      width: 250,
      accessor: 'toe_id',      

    }, {
      Header: 'Confirm',
      id: 'confirm',
      width: 130,
      Cell: (props) => <button type="button" onClick={toeSearchButtonEvent(props)}>
        Confirm Match
      </button>
     
    },

I am trying to pass the properties of the button to this function below so that when clicked, I get the properties of the row:

function toeSearchButtonEvent(props) {
    console.log(props)        
    
  }

However, the current behavior is that all the properties of all the rows are printed to the console all at once and the onClick event of the button on each row is not triggered when clicked. How do I get the desired behavior of just getting the property of the row of the button I click?

2 Answers

You can call toeSearchButtonEvent prop in Cell like below

Just a side note, you should not call onClick={toeSearchButtonEvent(props)} directly. It will trigger toeSearchButtonEvent without a click event. You can wrap it with another anonymous function onClick={() => props.toeSearchButtonEvent(props)}.

{
      Header: 'Toe ID',
      id: 'toe_id',
      width: 250,
      accessor: 'toe_id',      

    }, {
      Header: 'Confirm',
      id: 'confirm',
      width: 130,
      Cell: (props) => <button type="button" onClick={() => props.toeSearchButtonEvent(props)}>
        Confirm Match
      </button>
     
    },

And then render Cell with toeSearchButtonEvent

<Cell {...props} toeSearchButtonEvent={toeSearchButtonEvent} />

{...props} is representive of all your other props which you pass to Cell.

You can call toeSearchButtonEvent prop in Cell like below

{
      Header: 'Toe ID',
      id: 'toe_id',
      width: 250,
      accessor: 'toe_id',      

    }, {
      Header: 'Confirm',
      id: 'confirm',
      width: 130,
      Cell: ({row:{original}}) => <button type="button" onClick={props.handlerClick.bind(this,original)}>
        Confirm Match
      </button>
     
    },
Related