Created
April 20, 2021 18:50
-
-
Save prdxs/1b8b1b29970a2178350e3b3b90bc6f12 to your computer and use it in GitHub Desktop.
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 StoppableClock extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
time: new Date().toLocaleTimeString(), | |
isRunning: true, | |
}; | |
} | |
componentDidMount() { | |
this.intervalId = setInterval(() => { | |
this.setState({ time: new Date().toLocaleTimeString() }); | |
}, 1000); | |
} | |
componentWillUnmount() { | |
clearInterval(this.intervalId); | |
} | |
componentDidUpdate(prevProps, prevState) { | |
// Stopping clock | |
if (prevState.isRunning && !this.state.isRunning) { | |
clearInterval(this.intervalId); | |
} | |
// Re-starting clock | |
if (!prevState.isRunning && this.state.isRunning) { | |
this.intervalId = setInterval(() => { | |
this.setState({ time: new Date().toLocaleTimeString() }); | |
}, 1000); | |
} | |
} | |
toggle = () => { | |
this.setState(({ isRunning }) => ({ isRunning: !isRunning })); | |
} | |
render() { | |
const { className, style } = this.props; | |
const { time } = this.state; | |
return ( | |
<div className={clsx('StoppableClock', className)} style={style}> | |
<span className="StoppableClock-time">{time}</span> | |
<button className="StoppableClock-button" onClick={this.toggle}>Toggle</button> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment