Last active
April 20, 2021 11:47
-
-
Save prdxs/58e368b95760076c31ce7a9c8e64981a 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); | |
} | |
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