React Countdown Timer Component

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be building a countdown timer component using React. The timer will accept props for the starting time and will render a visual representation of the time left. It will also include buttons to pause, resume, and restart the timer, and will display a message when the time runs out. By completing this lab, you will gain experience using state and effects in React to build dynamic and interactive components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38346{{"`React Countdown Timer Component`"}} react/event_handling -.-> lab-38346{{"`React Countdown Timer Component`"}} react/conditional_render -.-> lab-38346{{"`React Countdown Timer Component`"}} react/hooks -.-> lab-38346{{"`React Countdown Timer Component`"}} react/use_state_reducer -.-> lab-38346{{"`React Countdown Timer Component`"}} end

Countdown Timer

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This code creates a countdown timer that prints a message when it reaches zero. To implement it, the following steps are taken:

  1. Use the useState() hook to create a state variable time that holds the time value. Initialize it from the props and destructure it into its components.
  2. Use the useState() hook to create the paused and over state variables, which are used to prevent the timer from ticking if it's paused or the time has run out.
  3. Create a method tick, that updates the time values based on the current value (i.e. decreasing the time by one second).
  4. Create a method reset, that resets all state variables to their initial states.
  5. Use the the useEffect() hook to call the tick method every second via the use of setInterval() and use clearInterval() to clean up when the component is unmounted.
  6. Use String.prototype.padStart() to pad each part of the time array to two characters to create the visual representation of the timer.
const CountDown = ({ hours = 0, minutes = 0, seconds = 0 }) => {
  const [paused, setPaused] = React.useState(false);
  const [over, setOver] = React.useState(false);
  const [[h, m, s], setTime] = React.useState([hours, minutes, seconds]);

  const tick = () => {
    if (paused || over) return;
    if (h === 0 && m === 0 && s === 0) setOver(true);
    else if (m === 0 && s === 0) setTime([h - 1, 59, 59]);
    else if (s == 0) setTime([h, m - 1, 59]);
    else setTime([h, m, s - 1]);
  };

  const reset = () => {
    setTime([parseInt(hours), parseInt(minutes), parseInt(seconds)]);
    setPaused(false);
    setOver(false);
  };

  React.useEffect(() => {
    const timerID = setInterval(tick, 1000);
    return () => clearInterval(timerID);
  });

  return (
    <div>
      <p>
        {`${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}:${s
          .toString()
          .padStart(2, "0")}`}
      </p>
      {over && <div>Time's up!</div>}
      <button onClick={() => setPaused(!paused)}>
        {paused ? "Resume" : "Pause"}
      </button>
      <button onClick={reset}>Restart</button>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <CountDown hours={1} minutes={45} />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Countdown Timer lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like