Skip to content

Instantly share code, notes, and snippets.

@MHenderson
Created July 2, 2019 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MHenderson/6e084ddff166460eb0321e6d16092844 to your computer and use it in GitHub Desktop.
Save MHenderson/6e084ddff166460eb0321e6d16092844 to your computer and use it in GitHub Desktop.
Clock (State and Lifecycle)
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h2>'tis: {this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment