JSFiddle - React, Tailwind, and code Playground
HTML
<link href="https://fonts.googleapis.com/css?family=Mali" rel="stylesheet">
<div id="timer"></div>
CSS
body {
color: black;
text-align: center;
font-family: 'Mali', cursive;
}
button {
font-family: 'Mali', cursive;
border: 1px solid black;
color: black;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
p.hidden {
font-weight: bold;
color : red;
}
p.show {
font-weight: bold;
color : green;
}
React
class TimerInput extends React.Component {
render() {
return (
<div>
<h3>Input the desired time</h3>
<input type="number" value={this.props.seconds} onChange={this.props.handleChange} required />
</div>
);
}
}
class Minuteur extends React.Component {
constructor(props) {
super(props)
this.libelle = props.libelle
this.state = {
time: {},
seconds: props.seconds
}
this.timer = 0
this.startTimer = this.startTimer.bind(this)
this.decrease = this.decrease.bind(this)
this.handleChange = this.handleChange.bind(this);
}
secondsToTime(secs){
let hours = Math.floor(secs / 3600)
let divisor_for_minutes = secs % 3600
let minutes = Math.floor(divisor_for_minutes / 60)
let divisor_for_seconds = divisor_for_minutes % 60
let seconds = Math.ceil(divisor_for_seconds)
let timerObj = {
"h": hours,
"m": minutes,
"s": seconds
};
return timerObj;
}
handleChange(event) {
this.setState({
seconds: event.target.seconds
})
}
componentDidMount() {
let timeLeft = this.secondsToTime(this.state.seconds)
this.setState({
time: timeLeft
});
}
startTimer() {
if (this.timer == 0 && this.state.seconds > 0)
{
this.timer = setInterval(this.decrease, 1000)
}
}
decrease() {
let seconds = this.state.seconds - 1
this.setState({
time: this.secondsToTime(seconds),
seconds: seconds,
});
if (seconds == 0) {
clearInterval(this.timer);
}
}
render() {
return(
<div>
<p className={"btn-group pull-right " + (this.state.seconds == 0 ? 'show' : 'hidden')}>{this.libelle}</p>
<button onClick={this.startTimer}>Démarrer</button>
<p>{this.state.time.h} h {this.state.time.m} minutes {this.state.time.s} secondes</p>
</div>
);
}
}
const App = () => {
return (
<div>
<TimerInput...