Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I update div when the text content changes in React

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading