Skip to content

Instantly share code, notes, and snippets.

@dextar47
Last active March 24, 2019 11:02
Show Gist options
  • Save dextar47/7b966ffee2113da19c6530bf9af301a7 to your computer and use it in GitHub Desktop.
Save dextar47/7b966ffee2113da19c6530bf9af301a7 to your computer and use it in GitHub Desktop.
Clock in react
<div id="app"></div>
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
tick() {
this.setState({date: new Date()});
}
componentDidMount() {
this.timer = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<p>Today is {this.state.date.toLocaleTimeString()}</p>
);
}
}
ReactDOM.render(<Clock />, document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment