Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save balazimichal/15b1bd01bb7db4284af5c84b305e2358 to your computer and use it in GitHub Desktop.
Save balazimichal/15b1bd01bb7db4284af5c84b305e2358 to your computer and use it in GitHub Desktop.
React-playground-timer
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
this.stopTimer = this.stopTimer.bind(this);
this.startTimer = this.startTimer.bind(this);
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
stopTimer() {
clearInterval(this.timerID);
}
startTimer() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<button onClick={this.stopTimer} color='red'>Stop timer</button>
<button onClick={this.startTimer}>Start timer</button>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
</script>
<!--
Note: this page is a great way to try React but it's not suitable for production.
It slowly compiles JSX with Babel in the browser and uses a large development build of React.
To set up a production-ready React build environment, follow these instructions:
* https://reactjs.org/docs/add-react-to-a-new-app.html
* https://reactjs.org/docs/add-react-to-an-existing-app.html
You can also use React without JSX, in which case you can remove Babel:
* https://reactjs.org/docs/react-without-jsx.html
* https://reactjs.org/docs/cdn-links.html
-->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment