Page Content

Tutorials

Understanding Event Handling in React.js With Example

Event Handling in React.js

Event Handling in React.js
Event Handling in React.js

React event management is essential for dynamic and interactive user interfaces. Window events like scrolling and user activities like mouse clicks, keyboard inputs, and form submissions can be handled by React. Event handling in React.js is essential for developing dynamic, interactive websites that react to user input. Events are the mouse clicks, keyboard keys, and page scrolling that take place in the web browser. React offers a standardised and structured method for handling these events by combining JavaScript code with JSX, a syntax similar to HTML.

Key Characteristics of React Event Handling

Unlike native DOM event handling in React.js, React consistently and effectively manages events:

SyntheticEvent Wrapper: Event Wrapper Synthetic React wraps the browser’s Event interface with SyntheticEvent. This wrapper provides more uniform behaviour across web browsers while closely mimicking normal browser events, abstracting cross-browser gaps. The nativeEvent attribute on the SyntheticEvent provides access to the native event in case it is ever needed.

CamelCase Naming Convention: Naming Convention for CamelCase Instead of utilising HTML’s standard lowercase or dash-case for event handler names, React uses camelCase. Onclick, for instance, becomes onClick, and onchange, onChange.

Direct Function Assignment: Assignment of Direct Functions Instead of passing a string as the event handler, JSX allows you to pass a function directly. This keeps your code organised by combining your markup and JavaScript code.

Event Data Extraction: Extraction of Event Data Properties are provided by the SyntheticEvent object to extract pertinent event information. For example, the current input value for input elements can be captured using event.target.value. Event.target.id returns the clicked element ID for additional items.

Preventing Default Actions: Ending Default Behaviours Event.preventDefault() can stop browser operations like form submissions that refresh pages in React event handlers. Single-page applications (SPAs) handle data client-side without page reloads, hence this is needed.

How to Add Event Handlers

Props are used in React to add event handlers directly to your JSX elements. In comparison, you might choose items and then add event listeners to them in traditional web development. Among the many events that React supports are standard ones like onClick (for clicks), onChange (for input field changes), onFocus (for element focus changes), and onBlur (for element focus changes).

React applications’ interactivity depends on event handlers changing component states and initiating re-renders. React effectively updates only the appropriate virtual DOM components when state changes, resulting in performant apps. This is used to update class components’ states.setState() calls render() again. Functional components use React Hooks like useState() to manage state. State variables and functions in the useState Hook cause re-renders when changed.

Event Handlers in Different Component Types:

Class Components: To guarantee that this refers to the component itself, event handler functions in class components frequently need to be tied to the component object in the constructor. As an alternative, this can be automatically bound by using arrow functions as class properties.

Functional Components: React Hooks have made it possible for functional components to handle events and manage state and lifecycle without the requirement for classes. In functional components, event handlers are frequently defined immediately within the component’s scope, giving them implicit access to the state and props of the component without the need for explicit binding.

Code Example:

An input field that refreshes a preview, gives just-in-time validation feedback, and removes this feedback when the user clicks away will be used to demonstrate event handling in React.js in a FileNamer application.

import React, { useState } from 'react';

export default function FileNamer() {
    const [name, setName] = useState('');
    const [alert, setAlert] = useState(false);

    const handleNameChange = (event) => {
        setName(event.target.value);
    };

    const validateAndSave = (event) => {
        if (/\*/.test(name)) {
            event.preventDefault();
            setAlert(true);
            return;
        }
        setAlert(false);
        alert(`File name "${name}.js" saved successfully!`);
        console.log(`Submitting file name: ${name}.js`);
    };

    return (
        <div className="wrapper">
            <div className="preview">
                <h2>Preview: {name || 'your-file'}.js</h2>
            </div>

            <form onSubmit={validateAndSave}>
                <label>
                    <p>Name:</p>
                    <input
                        autoComplete="off"
                        name="name"
                        value={name}
                        onChange={handleNameChange}
                        onFocus={() => setAlert(true)}
                        onBlur={() => setAlert(false)}
                    />
                </label>

                {alert && (
                    <div className="popup">
                        <span role="img" aria-label="allowed">✅</span> Alphanumeric characters are allowed.
                        <br />
                        <span role="img" aria-label="not allowed">⛔</span> * is not allowed.
                    </div>
                )}

                <div>
                    <button type="submit">Save</button>
                </div>
            </form>
        </div>
    );
}

Output:

Preview: your-file.js

Name:

Save

Save the aforementioned code in the same directory as index.js, index.html, and FileNamer. CSS to execute this example.Create React App is used to construct a development environment that manages compilation and serving. Manually serving these files for rapid local testing without a build configuration is possible with a basic web server like Python or Node.js.

Explanation of the Code Example

useState for State Management: The FileNamer component declares two state variables name, which stores the value of the text input, and alert, which is a boolean that controls the visibility of a validation message using the useState Hook. React re-renders the component to reflect the modified state when setName or setAlert are called.

onChange for Input Control:

  • The onChange prop of the <input> element is configured to handleNameChange.
  • An event handler called handleNameChange is triggered each time the value of the input changes. The SyntheticEvent object is passed to it.
  • The current text in the input field is captured by event.target.value inside handleNameChange.
  • The input becomes a controlled component when setName(event.target.value) modifies the name state, which modifies the input’s value prop. React state is guaranteed to be the “single of truth” for the value of the input with this design.

onFocus and onBlur for User Feedback:

  • When the user clicks or tabs into the input field, onFocus is activated. Here, the validation message is displayed by using setAlert(true).
  • The input field loses focus when the user clicks outside or tabs away, activating ONBLUR. To conceal the notification, call setAlert(false). These give users just-in-time information without a form.

Form onSubmit and event.preventDefault():

  • An onSubmit prop is set to validateAndSave on the <form> element. Since onSubmit manages both button clicks and pressing Enter, this is typically used over setting onClick on the submit button for form submission.
  • The validateAndSave function first determines whether a banned character (*) is included in the input name.
  • Event.preventDefault() is invoked if * is present. SPAs use this to prevent the browser from restarting the page after a form submission.
  • The validation warning is then shown by calling setAlert(true). A success message appears and the notice is hidden if no prohibited characters are detected.

useEffect for Global Event Listeners (Window Clicks): To control side effects, such adding or removing event listeners from the global window object, utilise the useEffect Hook. Every time the alert state changes, the effect is activated. Set alert to true to add a global click event listener (handleWindowClick) to the window. This listener hides the pop-up if the user clicks outside the window by changing the alert to false.

Importantly, a cleaning function is returned by useEffect. This function is invoked either before the effect reruns because of dependency changes or when the component unmounts from the DOM. The cleanup function removes the global event listener to prevent memory leaks from superfluous listeners.

By using these event handling in React.js solutions, React developers may create highly dynamic, effective, and user-friendly online apps with a clean code base.

Handling Multiple Events and Choosing the Right One

A vast array of HTML event handlers are available to you through React. When you require the event to happen and what precise data you wish to retrieve from the SyntheticEvent object will determine the event handler you should use.

Timing of Events: Events Happen at Different Times. User contacts have several events. A onClick event follows a onBlur event (when an element loses attention). You can manage user data or schedule activities this way.

Information Provided: While some events have precise information, some do not. For instance, onKeyPress gives the key’s charCode when it is pushed, while onChange gives the entire input value.

Multiple Handlers on a Single Element: React allows you to add a number of event handlers to a single DOM element. This aids in handling many user actions on one component. OnFocus and onBlur can provide just-in-time information as users enter and exit input fields.

Conclusion

In conclusion, Event handling in React.js is essential for dynamic, interactive, and user-responsive apps. React uses SyntheticEvent to manage clicks, form inputs, attention shifts, and more across browsers. Clean, declarative coding is achieved by using camelCase for event names, direct function assignments, and controlled components. Functional components may efficiently manage state and side effects like window-level event listeners using hooks like useState and useEffect.

The ability to prohibit default behaviours and conditionally provide UI feedback improves user experience without page reloads. Knowing when and how to employ event handlers like onClick, onChange, onFocus, and onBlur helps developers manage complex interactions cleanly and predictably. Overall, React’s structured event handling in React.js framework simplifies user input management and promotes efficient, maintainable, and scalable online apps.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index