Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
React Countdown Timer Padding Not Working

I have a working countdown timer & have added an if statement to address adding a preceding zero to hours, minutes, and seconds when less than 10; however, single digits are still showing up without the padding. Can you please let me know what I did wrong with my if statement or use of this.state?

import React,{Component} from "react";

class Countdown extends Component{
    constructor(props){
        super(props);
            this.state={
            hours:"00",
            minutes:"00",
            seconds:"00"
           }   
        }

        componentDidMount(){
            let countDownDate = new Date();
             countDownDate.setHours(24,0,0,0);
           
             setInterval(
                function () {
                  let now = new Date().getTime();
                  let timeleft = countDownDate - now;
                  this.setState({
                    hours: Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
                    minutes: Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60)),
                    seconds: Math.floor((timeleft % (1000 * 60)) / 1000)
                  });
                }.bind(this), // we added the binding here
                1000
              );

                      
          if (this.state.hours < 10) {
            this.state.hours = "0"+this.state.hours;
        }
                  if (this.state.minutes < 10) {
            this.state.minutes = "0"+this.state.minutes;
          }
                  if (this.state.seconds < 10) {
            this.state.seconds = "0"+this.state.seconds;
        }
        }
   
         render(){    
    return (
        <>
        <div className="countdown-timer">
        <div className = "countdown-text">
          <p>DEAL ENDS<br></br> Hrs: Min: Sec:</p>
        </div>
        <div className="countdown-time">
        <p>{this.state.hours}:{this.state.minutes}:{this.state.seconds} </p>
            </div>
        </div>
        </>
        )
        }
    
}

export default Countdown;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You cannot change the value of state directly, this will not re render the react component, you should change the state value using this.setState only, below you will find the modified code, which you can check.

    import React,{Component} from "react";

class Countdown extends Component{
    constructor(props){
        super(props);
            this.state={
            hours:"00",
            minutes:"00",
            seconds:"00"
           }   
        }

        componentDidMount(){
            let countDownDate = new Date();
             countDownDate.setHours(24,13,0,0);
           
             setInterval(
                function () {
                  let now = new Date().getTime();
                  let timeleft = countDownDate - now;
                  const hour = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                  const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
                  const seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
                  this.setState({
                    hours: hour >= 10 ? hour : "0" + hour,
                    minutes: minutes >= 10 ? minutes : "0" + minutes,
                    seconds: seconds >= 10 ? seconds : "0" + seconds,
                  });
                }.bind(this), // we added the binding here
                1000
              );

                      
        }
   
         render(){    
    return (
        <>
        <div className="countdown-timer">
        <div className = "countdown-text">
          <p>DEAL ENDS<br></br> Hrs: Min: Sec:</p>
        </div>
        <div className="countdown-time">
        <p>{this.state.hours}:{this.state.minutes}:{this.state.seconds} </p>
            </div>
        </div>
        </>
        )
        }
    
}

export default Countdown;
about 4 years ago · Juan Pablo Isaza Relatório

0

There is no need to add if statements. Just check the conditions in your JSX expression itself like this: <p>{this.state.hours < 10 ? "0" + this.state.hours : this.state.hours} : {this.state.minutes < 10 ? "0" + this.state.minutes : this.state.minutes : {this.state.seconds < 10 ? "0" + this.state.seconds : this.state.seconds}</p>. It should work, tested. Link to working sandbox

Your resulting code below:

import React, { Component } from "react";

class Countdown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hours: "00",
      minutes: "00",
      seconds: "00"
    };
  }

  componentDidMount() {
    let countDownDate = new Date();
    countDownDate.setHours(24, 0, 0, 0);

    setInterval(
      function () {
        let now = new Date().getTime();
        let timeleft = countDownDate - now;
        this.setState({
          hours: Math.floor(
            (timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
          ),
          minutes: Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((timeleft % (1000 * 60)) / 1000)
        });
      }.bind(this), // we added the binding here
      1000
    );
  }

  render() {
    return (
      <>
        <div className="countdown-timer">
          <div className="countdown-text">
            <p>
              DEAL ENDS<br></br> Hrs: Min: Sec:
            </p>
          </div>
          <div className="countdown-time">
            <p>
              {this.state.hours < 10
                ? "0" + this.state.hours
                : this.state.hours}
              :
              {this.state.minutes < 10
                ? "0" + this.state.minutes
                : this.state.minutes}
              :
              {this.state.seconds < 10
                ? "0" + this.state.seconds
                : this.state.seconds}{" "}
            </p>
          </div>
        </div>
      </>
    );
  }
}

export default Countdown;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda