implements timer

This commit is contained in:
Francesco Esposito 2019-03-14 16:53:56 +01:00
parent c35626062a
commit 9f147f4885
4 changed files with 88 additions and 15 deletions

View File

@ -1,25 +1,14 @@
import React, { Component } from 'react';
import logo from './logo.svg';
import Timer from './components/Timer';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<h1>tomadoro</h1>
<Timer />
</div>
);
}

3
src/components/Timer.css Normal file
View File

@ -0,0 +1,3 @@
.timer {
font-size: 120px;
}

80
src/components/Timer.js Normal file
View File

@ -0,0 +1,80 @@
import React, { Component } from 'react';
import { Button } from 'reactstrap';
import './Timer.css';
class Timer extends Component {
constructor(props) {
super(props);
this.defaultSeconds = 1500;
this.state = {
seconds: this.defaultSeconds,
started: false
};
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
}
fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
tick() {
this.setState(state => ({
seconds: state.seconds -1
}));
}
startTimer() {
this.setState({ started: true })
this.interval = setInterval(() => this.tick(), 1000);
}
stopTimer() {
this.setState({ started: false });
clearInterval(this.interval);
}
resetTimer() {
this.stopTimer();
this.setState({ seconds: this.defaultSeconds});
}
render() {
return (
<div className="App">
<p class="timer">{this.fmtMSS(this.state.seconds)}</p>
<Button
size="lg"
color="success"
onClick={this.startTimer}
disabled={this.state.started}
>
START
</Button>
<Button
color="danger"
size="lg"
onClick={this.stopTimer}
disabled={!this.state.started}
>
STOP
</Button>
<Button
color="secondary"
size="lg"
onClick={this.resetTimer}
disabled={this.state.started}
>
RESET
</Button>
</div>
);
}
}
export default Timer;

View File

@ -1,6 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import App from './App';
import * as serviceWorker from './serviceWorker';