Show timer in 2 digits instead of one react-timer-hook

Viewed 588

I'm using react-timer-hook in my react application. It's working great but in the example the timer has two digits for hours, minutes and seconds but when I import it and use the timer as a component in my app, the stop watch is showing one digit and only gets to two digits when the value increase above 9. Can anyone assist me in adding a trailing zero if the time is less than 10?

This is the screenshot from the react timer hook.

enter image description here

And this is the screenshot when I'm using it.

enter image description here

Below is the code how I'm using it.

import React from "react"; 
import { useStopwatch } from "react-timer-hook"; 
export default function MyStopwatch() {    
const {seconds, minutes,hours, days, isRunning, start, pause, reset } =
useStopwatch({ autoStart: true });};   
return (
<>
<div>
<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>
</div>
</>   
); 
}
1 Answers

Well this is one option:

import React from "react"; 
import ReactDOM from 'react-dom'
import { useStopwatch } from "react-timer-hook"; 
export default function MyStopwatch() {    
  const {
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    reset,
  } = useStopwatch({ autoStart: true });

  const formatTime = (time) => {
    return String(time).padStart(2, '0')
  }

  return (
    <div>
      <span>{formatTime(hours)}</span>:<span>{formatTime(minutes)}</span>:<span>{formatTime(seconds)}</span>
    </div>
  ); 
}

ReactDOM.render(
  <MyStopwatch />,
  document.getElementById('container')
);

Playground version here https://codesandbox.io/s/react-playground-forked-byo61?file=/index.js

Related