DEV Community

Cover image for Two ways to auto focus React input element
Nitsan Cohen
Nitsan Cohen

Posted on

Two ways to auto focus React input element

If you want to focus an input element when the DOM mounts, you have to place a ref on your input element and trigger the focus function in the useEffect hook.

Calling that function in the useEffect hook is because the callback that we pass to this hook will be triggered only when the DOM finishes to mount. Otherwise, we risk triggering the focus function before the input element is on the screen.

But there is a more straightforward option. You can pass the autoFocus attribute to that input element.

Nevertheless, it is sometimes helpful to use the first option to focus on an input element. For instance, we want our user to focus on the last input element when refreshing the page or return to that page from another one.

The attached example stores the latest input value in the local storage. We have to use the state as well to cause a new render cycle and keep the newest value. We are also checking if there is a value before setting it to local storage. This is meant to prevent empty strings from being stored.

Live playground:

https://stackblitz.com/edit/react-8arjym?file=src/App.js

auto focus react


  • For more posts like this follow me on LinkedIn

  • I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay