- Forums
- ionic
- How To Implement Countdown Timer Clock In React With React-timer-hook With Context
Use this code to implement a timer counter in your react application using react-timer-hook [5230], Last Updated: Mon Jun 24, 2024
edw
Sun Nov 05, 2023
0 Comments
233 Visits
Today I was stuck on how to add a coundown counter in my ionic react app, found react-timer-hook and this is how I implemented in my Context Provider:
Source: /g/xampp8/htdocs/laravel/StudentTodo/ionic-rowley/ionic-rowleyV2
Start by installing react-timer-hook
$ npm install --save react-timer-hook
ContextProvider.tsx:
import { useTimer } from 'react-timer-hook';
...
export const ContextProvider = ({ children }:any) => {
...
const [numberofMinutes, setNumberofMinutes] = useState(5);
// TIMER
const expiryTimestamp:Date = new Date();
expiryTimestamp.setSeconds(expiryTimestamp.getSeconds() + (numberofMinutes * 60)); // 10 minutes timer
const {
totalSeconds,
seconds,
minutes,
hours,
days,
isRunning,
start,
pause,
resume,
restart,
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
...
return (
<StateContext.Provider value={{
....
totalSeconds,
seconds,
minutes,
hours,
days,
isRunning,
start,
pause,
resume,
restart,
}}>
{children}
</StateContext.Provider>
);
USAGE:
const Page: React.FC = () => {
const {seconds,minutes,restart} = useStateContext();
const minStyle = {
backgroundColor:'#000',
color:'#fff',
padding:'3px',
borderRadius: '7px',
margin: '2px'
}
return (
timer: <span style={minStyle}>{String(minutes).padStart(2, '0')}</span>:
<span style={minStyle}>{String(seconds).padStart(2, '0')}</span>
<button onClick={() => {
// Restarts to 5 minutes timer
const time = new Date();
time.setSeconds(time.getSeconds() + 300);
restart(time)
}}>Restart</button>
);
};
export default Page;