const { useState, useEffect, useRef } = React;
export const OTPGenerator = () => {
const [countdown, setCountdown] = useState(null)
const [otpCode, setOTPCode] = useState(null)
const [ctaDisabled, setCTADisabled] = useState(false)
const [expiredMsgVisible, setExpiredMsgVisible] = useState(false)
const timerRef = useRef()
const otpButtonHandler = () => {
if(timerRef.current) clearInterval(timerRef.current)
setOTPCode(Math.floor(100000 + Math.random() \* 900000))
setCountdown(5)
setCTADisabled(true)
timerRef.current = setInterval(() => {
setCountdown(prev => {
if (prev === 1) {
setCTADisabled(false)
clearInterval(timerRef.current)
}
return prev - 1
})
}, 1000)
}
useEffect(() => {
return () => {
if(timerRef.current) clearInterval(timerRef.current)
}
}, [])
return (
OTP Generator
{!!otpCode
? otpCode
: “Click ‘Generate OTP’ to get a code”
}
{countdown === null
? “”
: countdown > 0
? `Expires in: ${countdown} seconds`
: “OTP expired. Click the button to generate a new OTP.”}
<button
id="generate-otp-button"
onClick={otpButtonHandler}
disabled={ctaDisabled}
>
Generate OTP
)
};