React js Resend Otp Timer Simple Code

แชร์
ฝัง
  • เผยแพร่เมื่อ 29 ธ.ค. 2024

ความคิดเห็น •

  • @paradise_hope
    @paradise_hope  12 วันที่ผ่านมา

    import React, { useEffect, useRef, useState } from "react";
    const InputWithTimer = ({ initialTime = 30 }) => {
    const [time, setTime] = useState(initialTime); // Timer value
    const [inputValue, setInputValue] = useState(""); // User input
    const inputRef = useRef(null); // Reference to the input field
    // Timer logic
    useEffect(() => {
    const timer = setInterval(() => {
    setTime((prevTime) => (prevTime > 0 ? prevTime - 1 : 0)); // Countdown
    }, 1000);
    return () => clearInterval(timer); // Cleanup on unmount
    }, []);
    // Focus on the input field when the component mounts
    useEffect(() => {
    if (inputRef.current) {
    inputRef.current.focus();
    }
    }, []);
    // Handle input changes
    const handleInputChange = (e) => {
    setInputValue(e.target.value);
    };
    // Handle resend button click
    const handleResend = () => {
    setTime(initialTime); // Reset timer
    setInputValue(""); // Clear input
    if (inputRef.current) {
    inputRef.current.focus(); // Focus back on input
    }
    };
    return (


    {time > 0 ? (
    Time Remaining: {time}s
    ) : (
    Resend
    )}

    );
    };
    export default InputWithTimer;