Get object data and target element from onClick event in react js

Reactjs

Reactjs Problem Overview


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

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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

Solution 3 - Reactjs

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

Solution 4 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSunil tcView Question on Stackoverflow
Solution 1 - ReactjsJakob LindView Answer on Stackoverflow
Solution 2 - ReactjsCory RobinsonView Answer on Stackoverflow
Solution 3 - ReactjsVitalii AndrusishynView Answer on Stackoverflow
Solution 4 - Reactjsandr1oView Answer on Stackoverflow