I am new to react,and making app where I want to get data of the row being clicked on a table,I don't whether this approach is good or not need suggestions

So far i have used onClick listener but when I click on a table , it gives me [object,object] in console.log(contract),I have also tried to to use loop to view data in it but it gives me [object,object],here's my below code:

    <table id="mytable" cellSpacing="0" width="100%">
         <thead>
         <tr>
             <th>CarName</th>
             <th>DriverName</th>
             <th>Date</th>
             <th>Pickup</th>
         </tr>
         </thead>
          <tbody>

          {                                   
            this.state.contracts.map((contract,index)=>{
            return(
              <tr key={index}  data-item={contract} onClick={this.contractdetails}>
                            <td>{contract.car} </td>                                                       
                            <td>{contract.driver}</td>
                            <td>{contract.date}</td>
                            <td>{contract.pickup}</td>
              </tr>
                      )})

            }
          </tbody>
         </table>

onClickfunction

 contractdetails=(e)=>{
    const contract=e.currentTarget.getAttribute('data-item');
    console.log(contract)
};

1 Answers

1
Maheer Ali On Best Solutions

Use JSON.stringify while setting the data-item

<tr key={index}  data-item={JSON.stringify(contract)} onClick={this.contractdetails}>

And use JSON.parse() while accessing it.

contractdetails=(e)=>{
    const contract= JSON.parse(e.currentTarget.getAttribute('data-item'));
    console.log(contract)
};

A better way is to just set index as data-index and you can access it from the state

this.state.contracts.map((contract,index)=>{
            return(
              <tr key={index}  data-index={index} onClick={this.contractdetails}>
               ...
               ...

            }

You can access it like below

contractdetails=(e)=>{
    let index = +e.currentTarget.getAttribute('data-index')
    console.log(this.state.contracts[index]);
};