0
0
ReactDebug / FixBeginner · 4 min read

How to Handle onFocus and onBlur Events in React Correctly

In React, handle onFocus and onBlur by attaching these event handlers directly to elements like input. Use functions to update state or trigger actions when the element gains or loses focus, ensuring you use React's camelCase event names and functional components with hooks.
🔍

Why This Happens

Developers often try to use onfocus and onblur (all lowercase) or attach event handlers incorrectly in React, causing the events not to fire. React uses camelCase event names like onFocus and onBlur, and these must be passed as props to JSX elements. Also, forgetting to use functions or mixing up controlled/uncontrolled inputs can cause unexpected behavior.

jsx
import React from 'react';

function MyInput() {
  return <input onFocus={() => alert('Focused')} onBlur={() => alert('Blurred')} />;
}

export default MyInput;
Output
No alert shows when focusing or blurring the input because React does not recognize lowercase event names.
🔧

The Fix

Use React's camelCase event names onFocus and onBlur with functions passed as props. This ensures React listens to these events properly. You can also use useState to track focus state if needed.

jsx
import React, { useState } from 'react';

function MyInput() {
  const [focused, setFocused] = useState(false);

  return (
    <>
      <input
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        aria-label="Name input"
      />
      <p>{focused ? 'Input is focused' : 'Input is not focused'}</p>
    </>
  );
}

export default MyInput;
Output
When the input is focused, the text 'Input is focused' appears below; when blurred, it changes to 'Input is not focused'.
🛡️

Prevention

Always use camelCase event names like onFocus and onBlur in React. Use functional components and hooks for state management. Test your components by focusing and blurring inputs in the browser. Use linting tools like ESLint with React plugin to catch incorrect event names early.

⚠️

Related Errors

Common related errors include using onClick instead of onFocus for focus events, or mixing controlled and uncontrolled inputs causing focus issues. Another is forgetting to bind event handlers in class components (legacy approach). Always prefer functional components with hooks.

Key Takeaways

Use React's camelCase event names onFocus and onBlur to handle focus events.
Attach event handlers as functions directly to JSX elements.
Use React hooks like useState to track focus state if needed.
Test focus and blur behavior in the browser to ensure handlers work.
Use linting tools to catch incorrect event names early.