To implement a countdown timer in React, you can follow these steps:
import React, { useState, useEffect } from 'react';
const CountdownTimer = ({ seconds }) => {
const [timeLeft, setTimeLeft] = useState(seconds);
useEffect(() => {
const timer = setInterval(() => {
setTimeLeft(timeLeft => timeLeft - 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<div>
<h1>{timeLeft}</h1>
</div>
);
}
export default CountdownTimer;
import React from 'react';
import CountdownTimer from './CountdownTimer';
const App = () => {
return (
<div>
<h1>Countdown Timer</h1>
<CountdownTimer seconds={60} />
</div>
);
}
export default App;
In the example above, the CountdownTimer component takes a prop seconds
to specify the initial countdown time in seconds. The component uses the useState
hook to keep track of the time left and the useEffect
hook to update the countdown timer every second.
You can customize the countdown timer by adding CSS styles or additional functionality as needed for your application.