ReactJS - FocusEvent Handler



In React 18 there is an event handler called FocusEvent which is an important component of web development. They allow us to track when a web page element gains or loses focus. These events can be handled in React by utilizing the onFocus and onBlur event handlers. So we will see the syntax and a small application to showcase the use of this event handler function.

Syntax

<input
   onFocus={e => console.log('onFocus')}
   onBlur={e => console.log('onBlur')}
/>

FocusEvent Functions

To handle focus-related events, React provides us two event handlers −

  • onFocus − This event handler is called when an element obtains focus.

  • onBlur − This event handler is called when an element loses focus.

Focus and Blur Events

When we click on an input field such as a button or any other active element in web development it becomes the focus element. When we click somewhere else or hit the 'Tab' key to switch to another element so the original element loses focus, which is referred to as a blur event.

FocusEvent Object

In React, when one of these focus events happens an event object (which is commonly referred to as e) is provided to the event handler method. This object holds event-related data. The event object contains certain extra properties for focus events, like relatedTarget, and inherits features from UIEvent, such as detail and view.

  • relatedTarget − This attribute shows which element is getting or losing attention.

  • detail − This property is often used to store additional data about the event.

  • view − This attribute relates to the window in which the event took place.

Examples

Example − Focus Event on Input Field

Now, let's put the concept into practice by creating a small React app that console logs messages when an input field gets and loses focus.

import React from "react";

function App() {
   return (
      <div>
         <>
            <input
               onFocus={(e) => console.log("I am onFocus")}// onFocus Event
               onBlur={(e) => console.log("I am onBlur")} // onBlur Event
            />
         </>
      </div>
   );
}

export default App;

Output

focus event

onFocus={(e) => console.log("I am onFocus")} − This part states that when we click or "focus" on the input field, it should do something. And it should log the message "I am onFocus" to the console. This is a way to track when the input field gets our attention.

onBlur={(e) => console.log("I am onBlur")}− Similarly, when we click away from or "blur" from an input field, it will show the message "I am onBlur" to the console.

Example − Check Password Strength

In this app we will create a password length checker app. Which allows users to enter a password in an input field. So we will use the React FocusEvent handlers to provide feedback on password strength when the input is focused and blurred.

import React, { useState } from "react";

function PasswordStrengthApp() {
   const [password, setPassword] = useState("");
   const [strengthMessage, setStrengthMessage] = useState("");   
   const handleFocus = () => {
      setStrengthMessage("Please enter a password");
   };   
   const handleBlur = () => {
      
      // Check password strength and provide feedback
      if (password.length === 0) {
         setStrengthMessage("Password cannot be empty");
      } else if (password.length < 6) {
         setStrengthMessage("Weak password: Too short");
      } else if (password.length < 10) {
         setStrengthMessage("Moderate password: Could be stronger");
      } else {
         setStrengthMessage("Strong password!");
      }
   };   
   const handleChange = (e) => {
      setPassword(e.target.value);
   };
   
   return (
      <div>
         <label>Password: </label>
         <input
            type="password"
            value={password}
            onChange={handleChange}
            onFocus={handleFocus}
            onBlur={handleBlur}
         />
         <div>{strengthMessage}</div>
      </div>
   );
}

export default PasswordStrengthApp;

Output

check password strength

In this app, the user receives feedback on the strength of the entered password when the input field is focused and blurred. The strength is evaluated based on the length of the password. We can enhance this app further by adding more password strength criteria.

Example − Form Validation App

Let us create a React app for a simple Form Validation using FocusEvent handlers. So in this app we will create a form with input fields for name and email. And then we will use React FocusEvent handlers to provide real-time validation feedback when the user focuses on and leaves each input field. And then we will display messages to show whether the entered name and email are valid.

import React, { useState } from "react";

function FormValidationApp() {
   const [name, setName] = useState("");
   const [email, setEmail] = useState("");
   const [nameError, setNameError] = useState("");
   const [emailError, setEmailError] = useState("");   
   const validateName = () => {
      if (!name.trim()) {
         setNameError("Name cannot be empty");
      } else {
         setNameError("");
      }
   };   
   const validateEmail = () => {
      
      // Basic email validation regex
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;      
      if (!email.trim()) {
         setEmailError("Email cannot be empty");
      } else if (!emailRegex.test(email)) {
         setEmailError("Invalid email format");
      } else {
         setEmailError("");
      }
   };

   return (
      <div>
         <form>
            <div>
               <label>Name: </label>
               <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  onFocus={validateName}
                  onBlur={validateName}
               />
               <div style={{ color: "red" }}>{nameError}</div>
            </div>               
            <div>
               <label>Email: </label>
               <input
                  type="text"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  onFocus={validateEmail}
                  onBlur={validateEmail}
               />
               <div style={{ color: "red" }}>{emailError}</div>
            </div>
         </form>
      </div>
   );
}

export default FormValidationApp;

Output

form validation app

In this app, the user receives real-time validation feedback for the name and email fields. Messages to indicate whether the entered information is valid are displayed when the user focuses on and leaves each input field. We can customize the validation logic based on the specific requirements.

Summary

Basically, it displays a website with an empty input field and listens for when we click into it (focus) and when we click away from it (blur), logging messages in the console to inform us when these events occur. It is a basic example to understand how to work with focus events in React.

reactjs_reference_api.htm
Advertisements