Skip to content
Advertisement

Start the timer when button is clicked in React.Js

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement