66

This is my code. I want to get both data in object & target element using onClick event. Can anyone help me.

handleClick = (data) => {
    console.log(data);
}

<input type="checkbox" value={data.id} defaultChecked={false} onClick={this.handleClick.bind(null, data)}/>
Sunil tc
  • 2,482
  • 4
  • 19
  • 46

4 Answers4

106

What about using an arrow function in the onClick handler?

handleClick = (e, data) => {
    // access to e.target here
    console.log(data);
}

<input type="checkbox" value={data.id} defaultChecked={false} onClick={((e) => this.handleClick(e, data))}/>
allencoded
  • 7,015
  • 17
  • 72
  • 126
Jakob Lind
  • 1,412
  • 1
  • 9
  • 4
  • and if I want to remove that event listener, how do i do that? – sandrina-p Mar 22 '17 at 10:07
  • By removing you mean that nothing should happen? You could have an if-check in your handleClick function which check if some prop is set, and then just return. Does that make sense? – Jakob Lind Mar 22 '17 at 14:01
  • 6
    You might want to find a different way to accomplish this. Arrow functions in JSX are considered bad practice: https://stackoverflow.com/questions/36677733/why-shouldnt-jsx-props-use-arrow-functions-or-bind. – Palisand Nov 07 '17 at 23:56
22

You can use data- element attributes and they'll be available in the target element:

import React from 'react'

export default MyComponent = () => {
  const onClick = event => {
    console.log(event.target.dataset.user)
  }

  return <div data-user="123" onClick={onClick}>Click me!</div>
}
Cory Robinson
  • 4,616
  • 4
  • 36
  • 53
15

Try this variant of code:

handleClick = (data, e) => {
    console.log(e.target.value, data);
}

<input type="checkbox" value={data.id} defaultChecked={false} onClick={this.handleClick.bind(this, data)}/>
Vitalii Andrusishyn
  • 3,984
  • 1
  • 25
  • 31
  • 1
    I realize this is a few years old now, but thought this worth a mention. I think that using `.bind()` in the assignment of the `onClick` property suffers the same problem as using an arrow function in this context. That issue being that each time render is called, it is considered a different object being assigned and therefore causes a re-render of the component. (Admittedly trivial for an HTML checkbox in this case.) – Ken Lyon May 30 '19 at 15:29
  • In your component constructor, you could have `this.handleClick = this.handleClick.bind(this);` although it would not know about `data`, which was the original point. I think data needs to be included in the event object, perhaps in the value. – Ken Lyon May 30 '19 at 15:35
2

First, if you bind null you won't get any context nor UIEvent object.

You need to change your onClick to 'onClick={this.handleClick}`.

And your handle function should look like

handleClick = (event) => {
    const { target: { value } } = event;

    // And do whatever you need with it's value, for example change state 
    this.setState({ someProperty: value });
};
andr1o
  • 249
  • 3
  • 7