Last active
November 4, 2016 16:30
-
-
Save ernestlv/530d5d3e99a310fa129465efb6b24f9d to your computer and use it in GitHub Desktop.
Timer written in ReactJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>React Timer</title> | |
<script src="https://unpkg.com/react@15.3.0/dist/react.js"></script> | |
<script src="https://unpkg.com/react-dom@15.3.0/dist/react-dom.js"></script> | |
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> | |
</head> | |
<body> | |
<div id="content"></div> | |
<script type="text/babel"> | |
class Timer extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { time: 30 }; | |
} | |
updateCounter() { | |
if (this.state.time > 0){ | |
//arrow function properly pass the state value (prevState) to update | |
this.setState( prevState => ( {time: --prevState.time} ) ); | |
}else{ | |
this.pauseTimer(); | |
} | |
} | |
startPauseTimer(e) { | |
this.counterID = !this.counterID ? setInterval(e => this.updateCounter(e), 1000) : clearInterval(this.counterID); | |
} | |
resetTimer(e) { | |
this.setState({time: 30}); | |
} | |
render() { //execute each time state changes | |
return ( | |
<div className="timer"> | |
Time: {this.state.time}<br /> | |
{/* arrow function properly binds "this" to the react component */} | |
<button onClick={e => this.startPauseTimer(e)}>start-pause</button> <button onClick={e => this.resetTimer(e)}>reset</button> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Timer />, | |
document.getElementById('content') | |
); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment