Get object data and target element from onClick event in react js
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))}/>
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>
}
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)}/>
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 });
};