Building a pomodoro Timer with React
Ruman Maharjan
Posted on October 17, 2024
Step 1: Setting Up Your React App
create a new React app using Create React App
npx create-react-app pomodoro-timer
cd pomodoro-timer
npm start
Step 2: Creating the Timer Component
import React, { useState, useEffect } from 'react';
const Timer = ({ initialMinutes = 25, initialSeconds = 0 }) => {
const [minutes, setMinutes] = useState(initialMinutes);
const [seconds, setSeconds] = useState(initialSeconds);
const [isActive, setIsActive] = useState(false);
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
if (seconds === 0) {
if (minutes === 0) {
clearInterval(interval);
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
} else {
setSeconds(seconds - 1);
}
}, 1000);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isActive, minutes, seconds]);
const toggleTimer = () => setIsActive(!isActive);
const resetTimer = () => {
setMinutes(initialMinutes);
setSeconds(initialSeconds);
setIsActive(false);
};
return (
{minutes}:{seconds < 10 ? 0${seconds}
: seconds}
{isActive ? 'Pause' : 'Start'}
Reset
);
};
export default Timer;
Step 3: Adding the Timer to Your App
// App.js
import React from 'react';
import Timer from './Timer';
import './App.css';
function App() {
return (
Pomodoro Timer
);
}
export default App;
/* App.css */
.App {
text-align: center;
font-family: Arial, sans-serif;
margin-top: 100px;
}
button {
margin: 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.timer h1 {
font-size: 48px;
margin-bottom: 20px;
}
Step 4: Customizing and Enhancing the Timer
// Add this in App.js before rendering
const [workMinutes, setWorkMinutes] = useState(25);
type="number"
value={workMinutes}
onChange={(e) => setWorkMinutes(e.target.value)}
min="1"
max="60"
/>
Posted on October 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.