how to start timer after button is clicked in class component using life cycle methods

Viewed 27

I wanted to start the timer when i clicked on start timer button but i am not bale to do this facing some error says bind property not able to read and also nothing is showing on dom.

import React, { Component, useState } from "react";
import "../styles/App.css";
class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: 0, x: 0, y: 0 };
  }
  componentDidMount() {
    startTime = ()=>{
      this.timer = setInterval(() => {
        this.setState(prev=>{
          return {time : prev.time + 1}
        })
      }, 1000);
    }
    
  }

  componentWillUnmount() {
    clearInterval(timer)
  }

  render() {
    return(
    <>
    <span>Time :{this.state.time}</span>
    <button onClick={this.startTime.bind(this)}>Start Timer</button>
    </>
    )
  }
}

export default Timer;

1 Answers

you have to move the startTime function outside the componentDidMount, as you can see the below code. I hope this works.

import React from "react";
import "../styles/App.css";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: 0, x: 0, y: 0 };
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }
  
  startTime = ()=>{
      this.timer = setInterval(() => {
        this.setState(prev=>{
          return {time : prev.time + 1}
        })
      }, 1000);
    }
  render() {
    return(
    <>
    <span>Time :{this.state.time}</span>
    <button onClick={this.startTime.bind(this)}>Start Timer</button>
    </>
    )
  }
}

export default App;
Related