Event handling is a crucial part of any web application as the user performs numerous actions on the web. If your application does not respond to the user interactions, the user might lose interest in your website and leave.
We have already covered event handling in jQuery, and you might know that we can call events like onClick() using the inline attributes within the HTML. However, in React, events are handled quite differently. Unlike HTML, React calls event listeners through props that start with on, followed by the event name starting in capital letters. Behind the scenes, React uses a system called Synthetic Events. These events are the browser-agnostic wrappers around the native browser events.
In this article, we will explore different React Events and learn how to use them to handle user interactions effectively.
Common Events in React
There are numerous events in React, some of which we have already covered in jQuery, but we'll re-learn them with reference to React. The following are some commonly used events in React:
Mouse Events
These events are triggered when a user performs an action through the mouse:
- onClick: When an object is clicked.
- onDoubleClick: When the user double-clicks on an object.
- onMouseEnter: When the user drags the mouse to an object.
- onMouseLeave: When the user drags the mouse away from an object.
- onMouseMove: When the mouse is moving over an element.
To understand how these events work, let's create a component that changes the text of a heading when the user hovers over it. Create a new component in the src folder and name it as Hover.js.
Now, add the following code to it:
0
import React, { useState } from 'react';
function Hover() {
const [text, setText] = useState('Drag the Mouse Towards Me!');
const mouseEnterHandler = () => {
setText('Hi, thank you for coming towards me!');
};
const mouseLeaveHandler = () => {
setText('Drag the Mouse Towards Me!');
};
return (
<h1 onMouseEnter={mouseEnterHandler} onMouseLeave={mouseLeaveHandler}>
{text}
</h1>
);
}
export default Hover;
In the above code, I have set the initial value of the heading using the useState hook. Later, I declared an event handler that handles the mouseenter event and updates the component's state with setText. Similarly, I've declared an event handler for the mouseleave event and reset the component state using the same setText method. In return, I called the event handlers for both events.
In App.js:
import React from 'react';
import Hover from './Hover';
function App() {
return (
<div>
<Hover />
</div>
);
}
export default App;
Form Events
These events are triggered when the user performs an action on the HTML forms:
- onSubmit: When a user submits a form.
- onChange: When the user changes the value of an input element.
- onFocus: When the user clicks on an element and, it gets focused.
- onBlur: When an element loses focus.
To understand these events, let's create a component named FormEvent.js and add the following code to it:
import React from 'react';
function FormEvent() {
const submitHander = (event) => {
event.preventDefault(); // Prevents the default browser form submission
console.log('Form submitted successfully!');
};
return (
<form onSubmit={submitHandler}>
<button type="submit">Submit</button>
</form>
);
}
export default FormEvent;
In the above code, we have used the event.preventDefault method to prevent the browser from submitting the form by default. Using this method is crucial to make the component work.
In App.js:
import React from 'react';
import FormEvent from './FormEvent';
function App() {
return (
<div>
<FormEvent />
</div>
);
}
export default App;
Keyboard Events
These events are triggered when the user performs an action with the keyboard:
- onKeyDown: When the user is holding a key.
- onKeyUp: When the user releases the key.
- onKeyPress: When the user presses a key. It is the combination of both onKeyDown and onKeyUp events.
Let's create a component that triggers an action when the user presses the Enter key. Name your file as KeyPressEvent.js and add the following code to it:
import React from 'react';
function KeyPressEvent() {
const keyDownHandler = (event) => {
if (event.key === 'Enter') {
console.log('You Pressed the Enter Key!');
}
};
return <input type="text" onKeyDown={keyDownHandler} />;
}
export default KeyPressEvent;
In App.js:
import React from 'react';
import KeyPressEvent from './KeyPressEvent';
function App() {
return (
<div>
<KeyPressEvent />
</div>
);
}
export default App;
Focus Events
These events are triggered based on the focus state of an element:
- onFocus: When an element gets focused.
- onBlur: When an element loses focus.
Let's see a simple example to understand how these events work. Create a new component named FocusEvents.js and add the following code:
import React, { useState } from 'react';
function FocusEvent() {
const [focused, setFocused] = useState(false);
const styleInput = {
borderColor: focused ? 'red' : 'blue'
};
const focusHandler = () => {
setFocused(true);
};
const blurHandler = () => {
setFocused(false);
};
return (
<input type="text" style={styleInput} onFocus={focusHandler}
onBlur={blurHandler}
/>
);
}
export default FocusEvent;
In the above example, we have used the useState hook to check the focus state of the input field. We have defined a styling constant that uses the ternary operator to determine whether the field is focused or not and implements the corresponding styling. Then, 2 handlers are defined to handle the focus events and change the state of the component with setFocused. Lastly, in return, we have declared an input element and called the onFocus and onBlur events with the corresponding handlers.
In App.js:
import React from 'react';
import FocusEvent from './FocusEvent';
function App() {
return (
<div>
<FocusEvent />
</div>
);
}
export default App;
There is much more to cover in event handling with React since it is a vast topic, but as a beginner, you should first properly understand and practice what I've demonstrated in this article. You can learn more about event handling in React from other online resources, as it plays a crucial role in modern web design. In the next article, we will learn how to display data dynamically with conditional rendering and lists.