Event handling in React.js is a fundamental concept that allows developers to build interactive and dynamic web applications. Events allow us to take a static page with no ability of interaction between the visual page to the data and provide the user with the ability to interact with data and perform actions faster and smoother, for example the ability to submit data to a external API source without refreshing the entire page and causing poor performance or poor user experience. As a software engineer with experience in various web technologies, I’ve utilized React’s robust event handling mechanism extensively in my projects. In this article, I’ll share my insights and best practices on event handling in Reactjs, drawing from my personal experience.
Understanding Event Handling in React
Reactjs employs a synthetic event system, which is a wrapper around the native browser events. The browser itself utilise events to improve user experience and allow integration between user actions to the developer who write the code(onsubmit, onkeydown, onmouseover, onclick, just to name a few) This system provides a consistent API that works across different browsers, making event handling easier and more reliable. React’s synthetic events also improve performance by using event delegation and batching updates.
Basic Event Handling
In React, event handlers are typically added as props to JSX elements. These event handlers are written in camelCase rather than lowercase as in plain HTML. Here’s a simple example of onClick react synthetic event that is base on the browser on click event:
import React, { useState } from 'react';
function ClickButton() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<button onClick={handleClick}>Click me</button>
<p>You've clicked {count} times</p>
</div>
);
}
export default ClickButton;
In this example, the handleClick function is called whenever the button is clicked. The onClick prop is used to attach the event handler to the button element.
Arguments And Event Handlers
Sometimes, you need to pass additional arguments to your event handler. This can be done by using an arrow function or the bind method. Here’s how you can achieve that:
import React from 'react';
function ItemList({ items }) {
const handleClick = (item, event) => {
console.log('Item clicked:', item);
};
return (
<ul>
{items.map((item) => (
<li key={item.id} onClick={(event) => handleClick(item, event)}>
{item.name}
</li>
))}
</ul>
);
}
export default ItemList;
In this case, the handleClick function receives both the item and the event object when an item is clicked.
Handling Forms
Handling form events in React is straightforward. React provides controlled components that maintain their state via React state. Here’s an example of a simple form:
import React, { useState } from 'react';
function SimpleForm() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted:', name);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default SimpleForm;
In this example, the handleChange function updates the state with the input value, and the handleSubmit function logs the state when the form is submitted.
Event Pooling
React’s synthetic event system uses event pooling to improve performance. This means that the event objects are reused across different events. However, this can sometimes lead to issues if you want to access the event properties asynchronously. To avoid this, you can call event.persist():
import React from 'react';
function DelayedClickButton() {
const handleClick = (event) => {
event.persist();
setTimeout(() => {
console.log('Event target:', event.target);
}, 1000);
};
return <button onClick={handleClick}>Click me</button>;
}
export default DelayedClickButton;
Best Practices
- Keep Event Handlers Small: Event handlers should be small and focused. If the logic becomes too complex, consider breaking it down into smaller functions.
- Use Arrow Functions Judiciously: While arrow functions are convenient for passing parameters, they can lead to performance issues if used excessively in render methods due to the creation of new functions on each render.
- Debounce Expensive Handlers: For performance-sensitive events like
scroll
orresize
, debounce the event handler to reduce the number of times it is called.
Browser Events
Here’s is a list of browser native events in javascript that will help us understand what we can do with Reactjs
Event | Description | Usage Example |
---|---|---|
click | Triggered when an element is clicked. | Handling button clicks to submit a form or trigger an action. |
mouseover | Triggered when the mouse pointer is moved onto an element. | Changing styles or displaying tooltips on hover. |
keydown | Triggered when a key is pressed down. | Capturing key presses for shortcuts or form validation. |
submit | Triggered when a form is submitted. | Validating form data before sending it to the server. |
change | Triggered when the value of an input element changes. | Updating state in response to user input in forms. |
load | Triggered when a resource has finished loading. | Executing code after images, scripts, or other resources load. |
resize | Triggered when the browser window is resized. | Adjusting layout or re-rendering components on window resize. |
scroll | Triggered when an element is scrolled. | Loading more content as the user scrolls down (infinite scroll). |
focus | Triggered when an element gains focus. | Highlighting input fields when they are selected. |
blur | Triggered when an element loses focus. | Validating input fields when the user moves to the next field. |
dblclick | Triggered when an element is double-clicked. | Implementing double-click actions, like opening files. |
contextmenu | Triggered when the right mouse button is clicked. | Displaying a custom context menu. |
input | Triggered when the value of an input changes (more general). | Real-time form input validation. |
mousemove | Triggered when the mouse is moved within an element. | Creating custom cursors or drawing on a canvas. |
wheel | Triggered when the mouse wheel is scrolled. | Implementing custom scrolling behavior or zooming. |
keyup | Triggered when a key is released. | Detecting when a user finishes typing in a search box. |
keypress | Triggered when a key is pressed down and released. | Capturing key presses for input fields (deprecated in modern web). |
drag | Triggered when an element is dragged. | Implementing drag-and-drop interfaces. |
drop | Triggered when an element is dropped. | Handling file uploads or moving items in a list. |
touchstart | Triggered when a touch point is placed on the touch surface. | Detecting the beginning of a touch gesture on mobile devices. |
touchmove | Triggered when a touch point is moved along the touch surface. | Handling swipe gestures on mobile devices. |
touchend | Triggered when a touch point is removed from the touch surface. | Detecting the end of a touch gesture on mobile devices. |
All above events can be utilised in ReactJS but in some cases we’ll want to apply best practice as we mention above like debounce or throttling to prevent our web application from a crash and improve performance and user experience.
Conclusion
Event handling in Reactjs is a powerful feature that, when used correctly, can make your applications highly interactive and responsive. By understanding the basics of synthetic events, passing arguments, handling forms, and following best practices, you can harness the full potential of React’s event handling system. Whether you’re building simple components or complex applications, mastering event handling will significantly enhance your React development skills.
Lior Amsalem embarked on his software engineering journey in the early 2000s, Diving into Pascal with a keen interest in creating, developing, and working on new technologies. Transitioning from his early teenage years as a freelancer, Lior dedicated countless hours to expanding his knowledge within the software engineering domain. He immersed himself in learning new development languages and technologies such as JavaScript, React, backend, frontend, devops, nextjs, nodejs, mongodb, mysql and all together end to end development, while also gaining insights into business development and idea implementation.
Through his blog, Lior aims to share his interests and entrepreneurial journey, driven by a desire for independence and freedom from traditional 9-5 work constraints.
Leave a Reply