Handling events in React is a 2 step process:
- Define an event handler.
- We pass the event handler to the element that we want to monitor for events.
import React, { Component } from 'react';
class SearchBar extends Component {
render() {
return <input onChange = {this.onInputChange} />;
}
onInputChange(event) {
console.log(event.target.value);
};
}
export default SearchBar;
Step - 1: Defining an Event Handler
An event handler is a function that runs whenever an event happens. The below function is an event handler, it receives an argument called as "event", which has details about the triggered event.
onInputChange(event) {
console.log(event.target.value);
};
Step - 2: Associating the event handler with the element we want to monitor
We want to monitor for "change" event on <input>. So, we write onChange event on <input> (onChange event is vanilla HTML) and associate it with event handler function.
<input onChange = {this.onInputChange} />
We can also make use of ES6 arrow functions to combine these 2 steps into 1 like below:
<input onChange = { event => console.log(event.target.value)} />