Skip to content Skip to sidebar Skip to footer

How To Render Countdown Function With ReactJS

I've been trying to get the countDown() function to run automatically inside render() function, but can't seem to figure it out. Here's the code: import React from 'react'; import

Solution 1:

Use componentDidMount for starting the interval and clear it (to be sure) in componentWillUnmount too.

Then use the this.setState correctly

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 5,
      message: ''
    }
  }
  
  componentDidMount() {
    this.inter = setInterval(() => {
      if (this.state.count <= 0) {
        clearInterval(this.inter);
        this.setState({
          message: 'Click here to skip this ad'
        }); 
      } else {
        this.setState((prevState) => ({count: prevState.count - 1})); 
      }
    }, 1000);
  }
  
  componentWillUnmount() {
    clearInterval(this.inter);
  }
  
  render() {
    return (
      <div>
        <h1>
          {this.state.message ? this.state.message : this.state.count}
        </h1>
      </div>
    )
  }
}

ReactDOM.render(<Counter />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Solution 2:

I would recommend calling countDown in componentDidMount also it is recommended to store the interval and clear it anyway in componentWillUnmount.


Solution 3:

As is your countdown method will run indefinitely as you know is mostly the case with SetIntervals. Also try to avoid using onLoads to call event handlers. What you should do is make use of the component life cycle methods provided by React. Specifically ComponentDidMount() and ComponentDidUpdate() in your case.

For your countdown, try using something like this

class Clock extends React.Component {
    state = {
       counter: 10
    }

//immediately is triggered. This only happens once. And we have it immediately call our countdown
componentDidMount() {
    this.countDown()
}

countDown = () => {
    this.setState((prevState) => {
        return{
            counter: prevState.counter - 1
        }
    })
}

//will get called everyt time we update the component state
componentDidUpdate(){
    if(this.state.counter > 0){
        setTimeout(this.countDown, 1000) //calls the function that updates our component state, thus creating a loop effect
    }
}

render() {
    return (
        <div className="time">
            The time is: {this.state.counter}
        </div>
    );
}

}


Post a Comment for "How To Render Countdown Function With ReactJS"