A Pen by Matthew Henderson on CodePen.
Created
July 2, 2019 15:02
-
-
Save MHenderson/6e084ddff166460eb0321e6d16092844 to your computer and use it in GitHub Desktop.
Clock (State and Lifecycle)
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
<div id="root"> | |
<!-- This element's contents will be replaced with your component. --> | |
</div> |
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
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') | |
); |
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
<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