Event handlers are crucial for building interactive web applications in React. As web developers, we are used to handling click, submit or change events. Focus and blur events are less common, but just as important.

This guide will cover everything you need to know about using onFocus and onBlur event handlers in React.

onFocus event handler in React

Elements receive focus when users click on them or use keyboard to navigate to them. When that happens, you can use built-in onFocus event handler to run a function.

Browsers have built-in response to focus events. Focused elements usually have a border. In case of input fields, there’s also a blinking cursor that tells users they can start typing.

You can use onFocus to customize the response to focus events. For example, customize visual indicators of a focused element. Or perform some other side-effect when a certain element is focused.

Here’s an example where we use onFocus to display a text to help users provide correct input.

Try clicking the input to focus it.

This is just a tip of the iceberg of what you can do using onFocus in React.

Next, let’s look at the code:

Code is pretty simple. We use onFocus to handle the focus event. The handleFocus function is defined outside of JSX and it does two things:

  1. It sets focused state variable to true.
  2. It logs the instance of SyntheticEvent to the console.

For now, let’s focus on the state variable.

onBlur event handler allows you to run a function when focus is removed. In this example, we use it to set focused state variable to false.

Inside JSX, we do a simple conditional rendering to render the helper text when input element is in focus. Embedded ternary operator checks the focused state variable. If it’s true, it renders the paragraph (<p>) if it’s false, it returns null.

If you’re coming from HTML, this might be easier to understand:

onfocusin in HTML is onFocus in React.

onfocusout in HTML is onBlur.