3

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>
</>   
); 
}
IntelligentCancer
  • 59
  • 1
  • 1
  • 15
  • See this: https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript – drodil Nov 10 '21 at 08:19
  • Hi @drodil thanks for the link i think this could solve my problem but im using an external library and im new to react can you tell me how can i add this pad function to my code? – IntelligentCancer Nov 10 '21 at 08:28

1 Answers1

3

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

drodil
  • 2,292
  • 1
  • 22
  • 37