Home > front end >  How do I update div when the text content changes in React
How do I update div when the text content changes in React

Time:07-31

I am creating a wheres waldo web app. When creating the timer i have been able to get the timer working with the data in useRef, but i can not figure out how to update the div everytime the timer changes. Some help would be much appreciated.

Javascript:

    const hour = useRef('00');
    const second = useRef('00');
    const stopTime = useRef(false);


    const timerCycle = () => {
        if (stopTime.current === false) {
            second.current = parseInt(second.current);
            minute.current = parseInt(minute.current);
            hour.current = parseInt(hour.current)

        
            second.current = second.current   1;
        
            if (second.current === 60) {
                minute.current = minute.current   1;
                second.current = 0;
            }
            if (minute === 60) {
                hour.current = hour.current   1;
                minute.current = 0;
                second.current = 0;
            }
        
            if (second.current < 10 || second.current === 0) {
                second.current = '0'   second.current;
            }
            if (minute.current < 10 || minute.current === 0) {
                minute.current = '0'   minute.current;
            }
            if (hour.current < 10 || hour.current === 0) {
                hour.current = '0'   hour.current;
            }
        
            console.log(second.current, minute.current, hour.current);

            setTimeout(timerCycle, 1000);
            
        }
    }

JSX:

<div id="stopwatch">{hour.current}:{minute.current}:{second.current}</div>

CodePudding user response:

We can take a look how different libraries do this:

From react-use

import { useReducer } from 'react';

const updateReducer = (num) => (num   1) % 1_000_000;

export default function useUpdate() {
  const [, update] = useReducer(updateReducer, 0);

  return update;
}

Usage:

const update = useUpdate();

if (hour.current < 10 || hour.current === 0) {
  hour.current = '0'   hour.current;
  update()
}
  • Related