Best way to capture isolated input is to not use TextInputs.

Amarjit Jha
2 min readAug 7, 2022

--

A cleaner and whole new crack at capturing PINs or isolated key inputs for web projects.

1. Let’s eliminate the most obvious question.

Why not simply put “N” number of text boxes and get it done

Well, technically you can do that but with a lot of unwanted pain. It’s painless and far better from the experience standpoint.

I faced following challenges with the traditional method :

  • I did not want my users to focus into successive boxes without filling the trailing input boxes.
  • Witnessed a lag when moved the focus to next/previous sibling boxes upon Input, specially while deleting input backwards.
  • Comparatively too many scenario handling resulting in much larger & complex code than this.

Try this demo : https://jhaspider.github.io/react-capture-pin/

2. Implementation

I pulled this example from a React project I did recently but a bit vetting can help you integrated this in any front-end framework or even with vanilla JavaScript.

Step 1: Define a constant for length

const LENGTH = 5;

Step 2: Add a key-up event on the document.

useEffect(() => {
document.addEventListener("keyup", onKeyUp);
return () => document.removeEventListener("keyup", onKeyUp);
}, []);

Step 3: Manage the inputs / key-strokes in an array

  • Handle Backpress
  • Handle Enter press
  • Other keys block — ( Validate each input against a simple regular expression)
  • Store the final input when ( LENGTH == array.length)

Step 4: Render from the array

  • Render each inputs from the array
  • Render blank inputs (LENGTH -(minus) array.length)

Step 5: CSS to imitate Input box and a Blinking cursor

It’s done.

Find the repo at : https://github.com/jhaspider/react-capture-pin

Hey — Care to give a clap before you go.

Cheers.

--

--

No responses yet