How to switch focus of ReactJS text-field components by pressing enter-key

Steve Kim
2 min readDec 14, 2019

--

Photo by Anthony Cantin on Unsplash

While I was building authentication text-fields with reactJS, I suddenly thought it should be able to change text-field focus with only pressing enter-key without mouse-clicks. It will improve user experience because users do not need to touch their mouse.

It looks something like this below.

We need the following dependencies.

  1. React ≥16.8.0 ,

We are using React Hooks, specifically “useState” and “useRef”, which are only available in the React versions of 16.8.0 or higher.

2. @material-ui/core

It is a CSS library that enables us to build components like text-field or buttons easily and quickly. There are so many of this kind of libraries out there. But material-ui seems to be the most popular so I chose to use it.

What I am trying to build is this.

There are 3 input components, two text-fields and one button. After filling in the first text-field, “username”, we need to be able to shift the focus to the second text-field, “password”, by just pressing “Enter” key. Then after filling in the second text-field,“password”, pressing “Enter” key also automatically clicks the button, “login”. In this way, users do not need to touch their mouse, which can help improve user experience.

Using “useRef” hooks is the key to achieving this functionality. As you see the code on codesandbox, I made 3 referencing variables, “textFieldForUsernameRef”, “textFieldForPasswordRef” and “buttonForLoginRef” with the useRef hook. Then I connected the three referencing variables with each react components with “inputRef” and “buttonRef”.

Please notice that the referencing variables do not refer to <TextField /> or <Button /> components, but it referencing DOM within the components. That’s why we use ‘inputProps” and “buttonProps”.

I just did it with 3 input components, but it can be done with however many components you have.

Thank you for reading my post. I am not sure if this is the optimal way. Please leave a comment if you get a better way to do it.

--

--

Steve Kim

A Certified Public Accountant / Hobbyist-programmer-but-dead-serious-specializing JavaScript, ReactJS, NextJS, Rust and AWS.