Created
February 4, 2020 18:26
-
-
Save thomas-lebeau/6fb6f0c9d328b2f021fe04094b6670cf to your computer and use it in GitHub Desktop.
migracode clock ticking
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
import React, { Component } from "react"; | |
import ReactDOM from "react-dom"; | |
class Time extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
date: new Date(), | |
count: 0 | |
}; | |
} | |
componentDidMount() { | |
this.start(); | |
} | |
componentWillUnmount() { | |
this.pause(); | |
} | |
pause = () => { | |
clearInterval(this.timerId); | |
}; | |
start = () => { | |
this.timerId = setInterval(this.tick, 1000); | |
}; | |
tick = () => { | |
console.log("tick", this.state.count); | |
this.setState(previousState => { | |
return { | |
date: new Date(), | |
count: previousState.count + 1 | |
}; | |
}); | |
}; | |
render() { | |
return ( | |
<div> | |
{this.state.date.toLocaleTimeString()} | |
<button onClick={this.pause}>pause</button> | |
<button onClick={this.start}>start</button> | |
</div> | |
); | |
} | |
} | |
class Clock extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { isShowingClock: true }; | |
} | |
toggle = () => { | |
this.setState(previousState => { | |
return { isShowingClock: !previousState.isShowingClock }; | |
}); | |
}; | |
render() { | |
return ( | |
<div> | |
{this.state.isShowingClock ? <Time /> : null} | |
<button onClick={this.toggle}>Toggle time</button> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<Clock />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment