Dr. Greg Bernstein
Updated April 20th, 2021
From react-lifecycle
class MyComponent extends React.Component {
constructor(props) {/*stuff*/ }
render() {/* stuff */ }
componentDidMount() {
// Called right after the component is created
// in the DOM
}
componentWillUnmount() {
// Called right before the component is removed
// from the DOM
}
// Other life cycle methods are available
}
Let’s create a self contained clock component
Keeps the “latest time” as internal state
Updates itself every second to update the state
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date().toLocaleString()};
}
render() {
return <div>
<h2>The date and time is:</h2>
<h2>{this.state.date}</h2>
</div>
}
}
ReactDOM.render(
<Clock />, document.getElementById('root')
);
constructor
From constructor
this.state
setState()
in the constructor! This is the only exception to the rule that all state changes are made by calling setState()
It renders, but it doesn’t update.
We need to start and stop a timer that updates the state
Where should we do this?
Be careful with this!
tick() { // function to call on timer ticks, see use of setState!
this.setState({date: new Date().toLocaleString()});
}
componentDidMount() {// Note use of bind below:
this.timerId = window.setInterval(this.tick.bind(this), 1000);
}
componentWillUnmount() {
window.clearInterval(this.timerId);
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date().toLocaleString()};
}
tick() {
this.setState({date: new Date().toLocaleString()});
}
componentDidMount() {
this.timerId = window.setInterval(this.tick.bind(this), 1000);
}
componentWillUnmount() {
window.clearInterval(this.timerId);
}
render() {
return <div>
<h2>The date and time is:</h2>
<h2>{this.state.date}</h2>
</div>
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);