Categories
React Answers

How to Detect Whether an Input Element is Focused within React?

Spread the love

Sometimes, we want to detect whether an input element is focused within React.

In this article, we’ll look at how to detect whether an input element is focused within React.

Detect Whether an Input Element is Focused within React

To detect whether an input element is focused within React, we can use a state to keep track of when the element is focused or not.

For instance, we can write:

import React from "react";

export default function App() {
  const [focused, setFocused] = React.useState(false);
  const onFocus = () => setFocused(true);
  const onBlur = () => setFocused(false);

  return (
    <>
      <input type="text" onFocus={onFocus} onBlur={onBlur} />
      <p>{focused.toString()}</p>
    </>
  );
}

We call the useState hook to create the focused state.

Then we creatr the onFocus and onBlur functions that calls setFocused with true and false respectively.

Then we set the onFocus function as the value of the onFocus prop which makes it run when we focus on the input.

And we set the onBlur prop to the onBlur function which makes it run when we move our focus away from the input.

Now when we click in and out of the input, we see true and false displayed if we focus in and out of the input respectively.

Conclusion

To detect whether an input element is focused within React, we can use a state to keep track of when the element is focused or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *