Giter VIP home page Giter VIP logo

react-pin-code-example's Introduction

title date excerpt cover_image
React Pin-Code Input
August 29, 2022
React pin-code input no libraries
/images/posts/REACT-PIN-IMG8.png

If you had the need to create a Pin-code input before you probably found many external libraries online to solved your problem, and when it comes to raw solutions you problably found very complex solutions involving useRef for example.

I know i've been througth that, so i created a super simple yet usefull react pin-input, and this is what the final result:

react-pin-code

live demo


The main idea here is to use a ´string´ and the ´onKeyDown´ event on a input, heres how:

First lets create a array to dertemine our pin code size

const pinSize = 5; 
const pinArray = [...new Array(pinSize)];

The next step is to create our PIN state and map the pinArray to create our inputs:

const [PIN, setPIN] = useState("");
...

{pinArray.map((_,i) => (
  <input 
   value={PIN[i] ?? ""}
  />
))}

As you can see the major logic here is to have and manipulate a string and display it accordingly to the index. Also the nullish operator is used to avoid a undefined value.

Lets then create our handler function based on the onKeyDown event:

...
  function handleKeyDown(event){
    if (e.key === "Backspace") setPIN(PIN.slice(0, -1));
    else if (PIN.length + 1 > pinSize) return;
    else setPIN(PIN + e.key[0]);
  }

This implementation allows basicly any input but you can easily filter that using e.key.charCodeAt(0) to get de ASCII value and use it to filter the input value.

Now just implement it as folows:

  {pinArray.map((_,i) => (
   <input 
     value={PIN[i] ?? ""}
     onKeyDown={handleKeyDown}
   />
  ))}

Done, simple isn't it? Now just throw in some styles and you ready to go!!

Full Code with some styles:

export default function App() {
  const [PIN, setPIN] = useState("");
  const pinSize = 5;

  function handleKeyDown(e) {
    if (e.key === "Backspace") setPIN(PIN.slice(0, -1));
    else if (PIN.length + 1 > pinSize) return;
    else setPIN(PIN + e.key[0]);
  }

  return (
    <>
        <div style={{ display: "flex", gap: "1rem" }}>
          {[...new Array(pinSize)].map((_, i) => (
            <input
              value={PIN[i] ?? ""}
              onKeyDown={handleKeyDown}
              maxLength="1"
              style={{
                width: "5rem",
                height: "5rem",
                fontSize: "2rem",
                caretColor: "transparent",
                textAlign: "center",
                outline: `${PIN[i] !== undefined ? "4px solid orange":"0"}`,
              }}
            />
          ))}
        </div>
    </>
  );
}

react-pin-code-example's People

Contributors

vzsoares avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.