Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
React onCut Event
Next article icon

React onBlur Event

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In React, handling user interactions efficiently is important for building responsive and dynamic applications. One of the commonly used events for managing focus behaviour is the onBlur event. This event is important for tracking when a user moves the focus away from an element, such as an input field or a button.

In this article, we will explore the onBlur event in React, its purpose, how it works, and common use cases.

What is onBlur Event?

The onBlur event in React is a synthetic event that is triggered when an element loses focus. It is commonly used with form elements like input fields, text areas, and buttons to handle situations when the user moves away from an element, either by clicking elsewhere on the page or navigating to another element using the keyboard (e.g., pressing the "Tab" key).

Syntax

<Element onBlur={handleBlur} />
  • <Element>: The React component or HTML element (like input, textarea, etc.) you want to track the focus loss for.
  • handleBlur: The function that will be executed when the element loses focus. This function can be defined in your component.

It is similar to the HTML DOM onblur event but uses the camelCase convention in React.

When Does the onBlur Event Get Triggered?

The onBlur event gets triggered when an element loses focus. This can happen in several ways:

  • The user clicks outside the element.
  • The user presses the "Tab" key to navigate to another element.
  • The user clicks or focuses on another interactive element, such as a button or link.

Handling the onBlur Event

The onBlur event in React is fired when an element loses focus. This event is commonly used for performing actions after a user finishes interacting with an input field, such as form validation, UI updates, or saving data.

JavaScript
import React, { useState } from 'react';  function App() {     const [value, setValue] = useState('');      const handleBlur = () => {         console.log('Input blurred');     };      return (         <form action="">             <label htmlFor="">Name:</label>             <input                 type="text"                 value={value}                 placeholder='Write Your Name'                 onChange={                     (e) =>                      setValue(e.target.value)}                 onBlur={handleBlur}             />         </form>     ); }  export default App; 

Output

onBlurGIF
Handling the onBlur Event

In this code

  • A React component with a controlled input field using the useState hook.
  • The value state holds the input's current value.
  • The onChange event updates the value state as the user types.
  • The onBlur event triggers the handleBlur function and logs "Input blurred" when the input loses focus.

Preventing Default Behavior

In some cases, you may want to prevent certain default behaviors triggered by the onBlur event, such as re-focusing or unintended UI changes. We prevent the default form submission behavior using the onSubmit event in React, which is commonly used in forms. We'll use the event.preventDefault() method to stop the form from reloading the page when the user submits it. Instead, we handle the form submission programmatically.

JavaScript
import React, { useState } from "react";  function PreventDefault() {     const [value, setValue] = useState("");     const [message, setMessage] = useState("");          const handleSubmit = (event) => {         event.preventDefault();         if (!value.trim()) {             setMessage("Please enter something in the input field!");         } else {             setMessage(`Form submitted successfully with value: ${value}`);         }     };      const handleChange = (event) => {         setValue(event.target.value);         setMessage("");      };      return (         <div>             <h2>Form with Prevented Default Submission</h2>             <form onSubmit={handleSubmit}>                 <label>                     Enter Text:                     <input                         type="text"                         value={value}                         onChange={handleChange}                         placeholder="Type something"                     />                 </label>                 <button type="submit">Submit</button>             </form>              {/* Display the message based on form submission */}             {message && <p>{message}</p>}         </div>     ); }  export default PreventDefault; 

Output

prevention
Preventing Default Behavior


In this code

  • This React component prevents form submission from reloading the page using event.preventDefault().
  • It validates the input field on submission, displaying an error message if empty, or a success message with the entered value.
  • The input is managed using state, and the message is cleared when the user types.

Accessing the Event Object

The onBlur event handler in React receives an event object that provides details about the focus change. This event object is useful for accessing information such as the element that lost focus, the previous element, and other relevant data.

JavaScript
import React, { useState } from "react";  function AccessEvent() {     const [value, setValue] = useState("");      const handleChange = (event) => {         console.log("Event Object:", event);          console.log("Input Value:", event.target.value);          setValue(event.target.value);      };      return (         <div>             <h2>Access Event Object Example</h2>             <input                 type="text"                 value={value}                 onChange={handleChange}                  placeholder="Type something"             />             <p>Input Value: {value}</p>         </div>     ); }  export default AccessEvent; 

Output

access-
Accessing the Event Object

In this code

  • This React component logs the event object and input value whenever the user types in the input field.
  • The handleChange function updates the state with the input value (event.target.value) and logs the event details.
  • The current input value is displayed below the input field.

Using onBlur for Focus Validation

One common use case for the onBlur event is focus validation, which allows you to validate user input when they move focus away from an input field (e.g., checking if an email address is valid after they leave the input field).

JavaScript
import React, { useState } from "react";  function FocusValidation() {     const [email, setEmail] = useState("");     const [error, setError] = useState("");      const handleBlur = () => {         const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;         if (!regex.test(email)) {             setError("Please enter a valid email.");         } else {             setError("");         }     };      const handleChange = (event) => {         setEmail(event.target.value);     };      return (         <div>             <input                 type="email"                 value={email}                 onChange={handleChange}                 onBlur={handleBlur}             />             {error && <p style={{ color: "red" }}>{error}</p>}         </div>     ); }  export default FocusValidation; 

Output

blur-1-
Using onBlur for Focus Validation

Using onBlur for Toggling Edit Modes

We can also use the onBlur event to toggle between edit and view modes in a UI component, allowing users to edit a field and then automatically switch it back to a display mode when they finish.

JavaScript
import React, { useState } from "react";  function ToggleEdit() {     const [isEditing, setIsEditing] = useState(false);     const [value, setValue] = useState("Click to Edit");      const handleBlur = () => {         setIsEditing(false);      };      const handleChange = (event) => {         setValue(event.target.value);     };      return (         <div>             {isEditing ? (                 <input                     type="text"                     value={value}                     onChange={handleChange}                     onBlur={handleBlur}                  />             ) : (                 <p onClick={() => setIsEditing(true)}>{value}</p>              )}         </div>     ); }  export default ToggleEdit; 

Output

blur-12
Using onBlur for Toggling Edit Modes

In this code

  • Edit Mode: When the user clicks the displayed text (<p>), it switches to an input field, allowing them to edit the text. The onBlur event exits edit mode when the input loses focus.
  • Display Mode: The text is displayed as a paragraph (<p>). Clicking on the text switches it to edit mode.

Common Use Cases for React onBlur Event

The onBlur event in React is highly versatile and can be used to handle various interactions and enhance user experience. Below are some common use cases where onBlur can be particularly useful:

  • Form Validation: Trigger validation when a user exits an input field (e.g., check if an email is valid).
  • Auto-Saving: Automatically save data when the user finishes editing a field.
  • UI Updates: Change UI elements, like showing validation feedback or changing field styles.
  • Focus Management: Automatically move focus to the next field or step in a form.
  • Hide UI Elements: Hide tooltips, dropdowns, or popups when focus is lost.
  • Closing Modals: Close modals or popups when the user clicks away or moves focus.

Conclusion

The onBlur event in React is a powerful tool for handling user focus interactions. It provides a way to respond to changes in focus, such as validating input, displaying helpful messages, or formatting data. By understanding when and how to use onBlur, you can significantly improve the user experience in your React applications, especially when dealing with forms and interactive elements.


Next Article
React onCut Event

A

ashishbhardwaj18
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React Events

Similar Reads

  • React onCut Event
    React onCut Clipboard event is an event handler event, which detects the cut process in the browser. When the user starts cutting data through the shortcut key (CTRL + X) or the cut button present in the menu, this even automatically fires, and the function passed to it will call itself automaticall
    2 min read
  • React onClick Event
    The onClick event in React is used for handling a function when an element, such as a button, div, or any clickable element, is clicked. Syntax onClick={handleClick}Parameter The callback function handleClick which is invoked when onClick event is triggeredReturn Type It is an event object containin
    3 min read
  • React onFocus event
    The onFocus event in React is triggered when an element receives focus, meaning it becomes the active element that can accept user input. This event is commonly used to execute functions or perform actions when an element gains focus. It is similar to the HTML DOM onfocus event but uses the camelCas
    2 min read
  • React onKeyUp Event
    React onKeyUp is an event listener that is used to detect the key release event in a browser using JavaScript. This event occurs once after the key is pressed and released. It is similar to the HTML DOM onkeyup event but uses the camelCase convention in React. Syntax:<input onKeyUp={keyUpFunction
    2 min read
  • React onInput Event
    React onInput is an event handler that triggers then there is any change in the input field. It is fired immediately when the user is changing input. It is one of the form events that updates when the input field is modified. It is similar to the HTML DOM oninput event but uses the camelCase convent
    2 min read
  • React onSubmit Event
    The onSubmit event in React is an event handler that is triggered when a form is submitted. It allows you to handle form submissions and allows you to control what happens when a user submits a form, such as form validation, preventing the default submission behaviour, and executing custom logic lik
    5 min read
  • React onScroll Event
    React onScroll helps to listen for scroll interactions within specific elements and trigger actions accordingly. It triggers whenever the scrolling position changes within the specified element. It is useful when implementing infinite scrolling, parallax effects, lazy loading, or dynamic UI changes.
    4 min read
  • React onResize Event
    React onResize() event is not like onClick() or onChange(). Instead, developers can leverage the window object's resize event within the useEffect() hook to handle resizing events. It is similar to the HTML DOM onresize event but uses the camelCase convention in React. Syntax: const handleResize = (
    2 min read
  • React onCopy Event
    React onCopy Clipboard event is an event handler which detects the copy process in the browser using JavaScript. When the user starts copying data through the shortcut key (CTRL + C) or the copy button present in the menu, this even automatically fires, and the function passed to it will call itself
    2 min read
  • React onMouseUp Event
    React onMouseUp event is used to detect when a mouse button is released over an element. It triggers when the user releases a mouse button while the cursor is over an element. It is particularly useful where you want to detect the ending of a mouse click or drag operation. It is similar to the HTML
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences