-2

I want to pass id of th tag <th id='1' onClick={this.click.bind(this)}> to on click function. Suppose i want to print the id of <th> in click() function console.log. here is the code-

<thead>
 <tr>
    <th id='name' onClick={this.click.bind(this)}>Name</th>
    <th id='phone' onClick={this.click.bind(this)}>Phone number</th>
    <th id='email' onClick={this.click.bind(this)}>Email</th>
 </tr>
</thead>

the click() function-

click(){
console.log('the clicked id is:') //here i want the id
}
Steve Smith
  • 79
  • 3
  • 9

3 Answers3

0

Bind takes arguments

this.click.bind(this, 'phone')

click(phone) {
  // ...
}

or use es6 arrow functions

onClick={() => this.click('phone')}
Alexes
  • 230
  • 3
  • 9
0

You can do something like this:

const headers = [
  { id: 'name', label: 'Name' },
  { id: 'phone', label: 'Phone' },
  { id: 'Email', label: 'Name' },
]

const ab = (
  <thead>
    <tr>
      {headers.map(doc => (
        <th onClick={() => { this.click(doc.id) }}>{doc.label}</th>
      ))}
    </tr>
  </thead>
)
Ritesh Bansal
  • 3,108
  • 2
  • 16
  • 23
0

This should work:

<tr>
  <th id='name' onClick={this.foo}>Name</th>
  <th id='phone' onClick={this.foo}>Phone number</th>
  <th id='email' onClick={this.foo}>Email</th>
</tr>

The onclick function

   foo=(e)=> {
     console.log(e.target.id);
   }