Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

People also ask

How do you get the attribute value from event target in React?

Use the target. dataset property to access data attributes from the event object in React. The dataset property provides read and write access to the custom data attributes of the element.

How do I get the index of a clicked element in React?

To get the key index of an element on click in React:Add an onClick event listener to each element. Every time an element is clicked, call the handler function passing it the event and the key index.

How do you pass multiple parameters in onClick function in React?

But if in any function you want to pass any extra parameter, then you need to use either arrow function or bind that function by using . bind(this, parameter) . Note: Another thing that you need to change here is, the way you are updating the state values, You should never mutate state variable directly.


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

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

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

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