Search code examples
javascriptreactjsconditional-operator

How to make a shorter ternary conditional operator in a React functional component?


I made a countdown timer in React using useState and useEffect hooks; everything is working great however the ternary conditional operator for seconds, where I am prepending 0 and replacing the counter value 0 with 00 for display purposes seems a bit excessive. Is there a way to simplify/shorten this, maybe setting Math.floor((counter % (1000 * 60)) / 1000) to a variable in the return ()? Not sure how to do this in React.

return (
  <div className={styles.timer}>
    <span className={styles.minutes}>
      {Math.floor((counter % (1000 * 60 * 60)) / (1000 * 60))}
    </span>
    <span className={styles.colon}>:</span>
    <span className={styles.seconds}>
      {Math.floor((counter % (1000 * 60)) / 1000) === 0 ?
      `00` :
      Math.floor((counter % (1000 * 60)) / 1000) < 10 ?
      `0${Math.floor((counter % (1000 * 60)) / 1000)}` :
      Math.floor((counter % (1000 * 60)) / 1000)
      }
    </span>
  </div>
)

Solution

  • Turn it into a string, then .padStart with '0' to 2 characters.

    <span className={styles.seconds}>
      {
        String(Math.floor((counter % (1000 * 60)) / 1000))
          .padStart(2, '0')
      }
    </span>