Building a pomodoro Timer with React

ruman67

Ruman Maharjan

Posted on October 17, 2024

Building a pomodoro Timer with React

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"
/>

💖 💪 🙅 🚩
ruman67
Ruman Maharjan

Posted on October 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024