You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import { useTranslation } from 'react-i18next';
interface CountdownTimerProps { initialSeconds: number, onComplete?: Function }
export interface CountdownTimerRef { handleStop: Function, handleStart: Function, handleReset: Function, isActive: boolean }
const CountdownTimer = forwardRef<CountdownTimerRef, CountdownTimerProps>((props, ref) => {
const { initialSeconds, onComplete } = props const { t } = useTranslation() const [seconds, setSeconds] = useState(initialSeconds); const [isActive, setIsActive] = useState(false); const [title, setTitle] = useState('Send verification code')
useImperativeHandle(ref, () => ({ handleStop, handleReset, handleStart, isActive }))
const handleStop = () => { setIsActive(false); setTitle('Send verification code') };
const handleStart = () => { if (isActive) return setSeconds(initialSeconds) setIsActive(true); };
const handleReset = () => { setSeconds(initialSeconds); setIsActive(true); };
useEffect(() => { let interval: any = null;
if (isActive && seconds > 0) { interval = setInterval(() => { setSeconds(seconds => seconds - 1); }, 1000); } else { clearInterval(interval) seconds <= 0 && setTitle('Resend') setIsActive(false) // onComplete && onComplete(seconds)
}
return () => clearInterval(interval); }, [isActive, seconds, onComplete]);
return ( <div style={{ whiteSpace: 'pre-wrap' }}>{isActive ? <span className='fz-18 fw550'>{seconds}s</span> : t(title)}</div> ); });
export default CountdownTimer;
|