From d4df64c2de62254126d6a06d88c353d49b53a767 Mon Sep 17 00:00:00 2001 From: N Balgopal Patro <46865367+BalgopalPatro@users.noreply.github.com> Date: Mon, 31 Oct 2022 23:22:22 +0530 Subject: [PATCH] Create OTP.jsx --- open-source/src/pages/OTP.jsx | 98 +++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 open-source/src/pages/OTP.jsx diff --git a/open-source/src/pages/OTP.jsx b/open-source/src/pages/OTP.jsx new file mode 100644 index 0000000..c8935c4 --- /dev/null +++ b/open-source/src/pages/OTP.jsx @@ -0,0 +1,98 @@ +import { Input, Stack } from '@mui/material'; +import { useEffect, useRef, useState } from 'react'; + +const OtpInput = ({ value, setValue, ...others }) => { + const [otp0, setOtp0] = useState(''); + const [otp1, setOtp1] = useState(''); + const [otp2, setOtp2] = useState(''); + const [otp3, setOtp3] = useState(''); + + const inputRef0 = useRef(); + const inputRef1 = useRef(); + const inputRef2 = useRef(); + const inputRef3 = useRef(); + + const inputs = [ + { + name: 'otp0', + value: otp0, + inputRef: inputRef0, + setValue: (val) => setOtp0(val), + focusNext: () => inputRef1.current.focus(), + focusPrevious: () => {}, + }, + { + name: 'otp1', + value: otp1, + inputRef: inputRef1, + setValue: (val) => setOtp1(val), + focusNext: () => inputRef2.current.focus(), + focusPrevious: () => inputRef0.current.focus(), + }, + { + name: 'otp2', + value: otp2, + inputRef: inputRef2, + setValue: (val) => setOtp2(val), + focusNext: () => inputRef3.current.focus(), + focusPrevious: () => inputRef1.current.focus(), + }, + { + name: 'otp3', + value: otp3, + inputRef: inputRef3, + setValue: (val) => setOtp3(val), + focusNext: () => {}, + focusPrevious: () => inputRef2.current.focus(), + }, + ]; + + const handleChange = (e, idx) => { + if (e.key === 'Backspace') { + inputs[idx].setValue(''); + } + if (e.key === 'Backspace' && inputs[idx].value === '' && idx > 0) { + inputs[idx - 1].setValue(''); + inputs[idx].focusPrevious(); + } + if (/[0-9]/.test(e.key)) { + inputs[idx].setValue(e.key); + inputs[idx].focusNext(); + } + }; + + useEffect(() => { + const otp = otp0 + otp1 + otp2 + otp3; + setValue(otp); + }, [otp0, otp1, otp2, otp3, setValue]); + + return ( + + {inputs.map((input, idx) => ( + handleChange(e, idx)} + sx={{ + height: '80px', + fontFamily: 'Circular Std Medium', + fontSize: '48px', + lineHeight: '60px', + fontWeight: 500, + letterSpacing: '-0.02em', + color: 'primary.600', + }} + inputProps={{ + style: { + textAlign: 'center', + }, + }} + /> + ))} + + ); +}; + +export default OtpInput;