68

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)}/>

4 Answers 4

107

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))}/>
Sign up to request clarification or add additional context in comments.

3 Comments

and if I want to remove that event listener, how do i do that?
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?
You might want to find a different way to accomplish this. Arrow functions in JSX are considered bad practice: stackoverflow.com/questions/36677733/….
23

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>
}

Comments

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)}/>

2 Comments

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.)
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.
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 });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.