1
0

Added Timer component

This commit is contained in:
Christer Warén 2021-01-04 15:53:49 +02:00
parent 5568a22952
commit 5e1541f2f3
2 changed files with 99 additions and 0 deletions

46
src/Timer.css Normal file
View File

@ -0,0 +1,46 @@
.app {
text-align: center;
background-color: #282c34;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.time {
font-size: 3rem;
padding: 2rem;
}
.button {
padding: .6rem 1.5rem;
margin: .4rem;
border-radius: 3px;
text-transform: uppercase;
font-weight: 600;
font-size: .8rem;
border-style: groove;
}
.button:focus {
outline-width: 0;
}
.button-primary:hover {
background-color: #2641d4;
border: 1px solid #1b1f2b;
}
.button-primary-active {
background-color: #3151ff;
border: 1px solid #152684;
color: white;
}
.button-primary-inactive {
background-color: #3151ff;
border: 1px solid #152684;
color: white;
}

53
src/Timer.js Normal file
View File

@ -0,0 +1,53 @@
// I used code as basis to this Timer
// Build a React Timer Component Using Hooks by James King
// https://upmostly.com/tutorials/build-a-react-timer-component-using-hooks
import React, { useState, useEffect } from 'react';
const Timer = () => {
const [seconds, setSeconds] = useState(0);
const [isActive, setIsActive] = useState(false);
function toggle() {
setIsActive(!isActive);
}
function stop() {
setSeconds(0);
setIsActive(false);
}
useEffect(() => {
let interval = null;
if (isActive) {
interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
} else if (!isActive && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isActive, seconds]);
return (
<div className="timer">
<div className="time">
{seconds}s
</div>
<div className="row">
<button className={`button button-primary button-primary-${isActive ? 'active' : 'inactive'}`} onClick={toggle}>
{isActive ? 'Pause' : 'Start'}
</button>
<button className="button" onClick={stop}>
Stop
</button>
</div>
<button className="button" onClick={stop}>
Stop
</button>
</div>
);
};
export default Timer;