Event handling in React basically allows a user to interact with a web page and do something specific when a certain event occurs, such as a click or mouseover. When the user interacts with the application, events are fired, such as a mouseover, a key press, a change event, and so on. The application must handle the events and execute the code. In short, events are actions that javascript can react to.
Handling events with react have some syntactic differences from handling events on DOM. These are:
1. React events are named camelCase instead of lowercase.
2. With JSX, a function is passed as the event handler instead of a string. For example:
Event Declaration in plain HTML
<button onclick="showMessage()">
Hello TechieBundle
</button>
Event Declaration in React
<button onClick={showMessage}>
Hello TechieBundle
</button>
3. In react, we cannot return false to prevent the default behavior. We must call the preventDefault event explicitly to prevent the default behavior.
<a href="#" onclick="console.log('You had clicked a Link.'); return false">
Click_Me
</a>
In react, we can write it as:-
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}
The actions to which javascript can respond are called events. Handling events with react is very similar to handling events in DOM elements. Below are some general events that you would see in and out when dealing with react-based websites:
- Clicking an element
- Submitting a form
- Scrolling page
- Hovering an element
- Loading a webpage
- Input field change
- User stroking a key
- Image loading
In the above example, e is a Synthetic Event which defines according to the W3C spec.
Now let us see how to use Event in React.
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
companyName: ''
};
}
changeText(event) {
this.setState({
companyName: event.target.value
});
}
render() {
return (
<div>
<h2>Simple Event Example</h2>
<label htmlFor="name">Enter company name: </label>
<input type="text" id="companyName" onChange={this.changeText.bind(this)}/>
<h4>You entered: { this.state.companyName }</h4>
</div>
);
}
}
export default App;
In the above example, we have used only one component and added an onChange event. This event will trigger the changeText function, which returns the company name.
Also read | React Controlled Vs. Uncontrolled Component