0

On an onClick i am trying to call the delete function.What i need is the value of the tableItem's id which i can see in the UI but can't access it in order to delete the particular row.The scenario is : click->delete fn-> uses id -> deletes the row. I just need id to make that happen.Which i am unable to bring in the delete function.

import React from 'react';





export default class TradeTable extends React.Component {

 delete = (event) => {
  event.preventDefault();
  
  console.log(event.target.value+"wdccerfec")
 
  //I just need the value of table item id 


 }
 render() {


  var tableData = this.props.store.arr;



  return <div className="panel panel-default">
 
   <div className="panel-body tradeComponent div-background table-responsive">
    <table className="table table-striped tb div-lightbackground">

     <thead className="thead-dark ">
      <tr>
       <th>Commodity</th>
       <th>Date</th>
       <th>Side</th>
       <th>Qty (MT)</th>
       <th>Price (MT)</th>
       <th>CounterParty</th>
       <th>Location</th>
       <th></th>
      </tr>
     </thead>
     <tbody>
                 //Trade data is an array of objects
      {
       tableData.map(tableItem => {
        return (
         <tr>
          <td>{tableItem.tradeDate}</td>
          <td>{tableItem.commodity}</td>
          <td>{tableItem.side}</td>
          <td>{tableItem.quantity}</td>
          <td>{tableItem.price}</td>
          <td>{tableItem.counterparty}</td>
          <td>{tableItem.location}</td>
          <td>{tableItem.id}</td>
          <td>

           

<button type='submit' className="btn btn-primary table-style" value={tableItem.id} onClick={this.delete}  >
                <span className="glyphicon glyphicon-trash" aria-hidden="true"></span>
           </button>

          </td>
         </tr>)
       })
      }

     </tbody>
    </table>
   </div>
  </div>
 }
}
AConsumer
  • 2,461
  • 2
  • 25
  • 33
  • without testing, wouldn't onClick={() => this.delete(tableItem.id)} work? You'd need to update the function signature too, of course – Cassandra S. Mar 23 '18 at 08:27
  • No not working :( – AConsumer Mar 23 '18 at 08:28
  • Possible duplicate of [React js onClick can't pass value to method](https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method) –  Mar 23 '18 at 08:29

2 Answers2

1

You need to pass the id with onClick button

onClick={this.delete.bind(this, tableItem.id)}

then

delete = (id) => {

    console.log('Clicked item', id)
}
Liam
  • 6,517
  • 7
  • 25
  • 47
0
onClick={() => this.delete(tableItem.id)}

is working see the working demo

Chotala Paresh
  • 566
  • 4
  • 12