How do you make it so that whenever you click the start button, only then will the timer starts. Because right now, it starts at will.
class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; } tick() { this.setState(prevState => ({ seconds: prevState.seconds + 1 })); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div> Seconds: {this.state.seconds} <br /> <button onClick={this.tick}> Start </button> </div> ); } } ReactDOM.render(<Timer />, mountNode);
What should I put in the onClick attribute?
Advertisement
Answer
You will need to bind ‘tick’ to the component in the constructor and move the code for starting the timer from ‘componentDidMount’ to ‘tick’ like so:
class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; this.tick = this.tick.bind(this); // bind to the component } tick() { // start timer after button is clicked this.interval = setInterval(() => { this.setState(prevState => ({ seconds: prevState.seconds + 1 })); }, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div> Seconds: {this.state.seconds} <br /> <button onClick={this.tick}> Start </button> </div> ); } } ReactDOM.render(<Timer />, mountNode);
Hope that helps.