ReactJS

React — How to pass event or any other details to onClick or other event handlers

We may need to get a the event details in a onClick or onChange event handler.

Normal event handler will look like this.

<button onClick={ this.handleClick } >Save </button>
<input type="text" onChange={ this.handleChange } />

In the above case we are not passing any event details to handler function.

Consider the input example above, we need to get the input value in event handler, how do we do it? We need to pass the event details to the handler function. This is how to do it.

<input type="text" onChange={ (evt) => this.handleChange(evt) } />

The handleChange function

handleChange(evt) {
// ---------^ this variable will have the event details. //get the value of the input box
let value = evt.target.value;}

Similarly we can also send any other information to the event handler function.

render() {
let name = "Sput"; return <input type="text" onChange={ (evt, name) => this.handleChange(evt, name) } />
}

The handleChange function will look like this.

handleChange(evt, name) {
// --------------^ this variable will have the name details.
}

Hope this helps 🍺

Computer engineer interested in programming, electronics, application architecture, data visualization, automation and performance optimization.

Leave a Reply