0

I am working in Reactjs and i am using nextjs framework,Right now i am trying to use following code in index.js so i can display data (day month day etc),How can i do this ? Here is my code

<script>
function updateTimer() {
  future  = Date.parse("June 11, 2020 11:30:00");
  now     = new Date();
  diff    = future - now;

  days  = Math.floor( diff / (1000*60*60*24) );
  hours = Math.floor( diff / (1000*60*60) );
  mins  = Math.floor( diff / (1000*60) );
  secs  = Math.floor( diff / 1000 );

  d = days;
  h = hours - days  * 24;
  m = mins  - hours * 60;
  s = secs  - mins  * 60;
  document.getElementById("timer")
    .innerHTML =
      '<div>' + d + '<span>days</span></div>' +
      '<div>' + h + '<span>hours</span></div>' +
      '<div>' + m + '<span>minutes</span></div>' +
      '<div>' + s + '<span>seconds</span></div>' ;
}
setInterval('updateTimer()', 1000 );

</script>
<div id="timer"></div>
5
  • 2
    it's not recommended to directly manipulate dom in react/next. go in the react way and use state, that's easier. Commented Nov 9, 2022 at 10:57
  • @abolfazlshamsollahi Please explain your point Commented Nov 9, 2022 at 11:02
  • usually we don't use document.getElementById("timer").innerHTML type of code in react it is called directly manipulating the dom , instead we use state to change the dom when the specific value is changed. Commented Nov 9, 2022 at 11:07
  • @abolfazlshamsollahi so kindly tell me how can i do this ? Commented Nov 9, 2022 at 11:28
  • go read about react and how states work Commented Nov 9, 2022 at 11:29

1 Answer 1

2

Directly manipulating the DOM in React is not recommended. Instead you should create a React component which holds state to display the data you would like to display. Here's an example of a component that can display the data you parse into it.

const Timer = ({days, hours, mins, secs}) => {
    const h = useMemo(() => {return hours - days * 24;}, [hours, days]);
    const m = useMemo(() => {return mins - hours * 60;}, [mins, hours]);
    const s = useMemo(() => {return secs - mins  * 60;}, [secs, mins]);
    
    return (
        <>
            <div>{days}</div>
            <div>{h}</div>
            <div>{m}</div>
            <div>{s}</div>
        </>
    )
}

Now this <Timer> component can be rendered in a component which holds the state for the days, hours, minutes and seconds, with a useEffect() being triggered every second to update the countdown.

const Countdown = ({futureDate}) => {
    const [future, setFuture] = useState(futureDate);
    const [days, setDays] = useState(0);
    const [hours, setHours] = useState(0);
    const [mins, setMins] = useState(0);
    const [secs, setSecs] = useState(0);

    useEffect(() => {
        const timer = setInterval(() => {
            //runs every second to update data's state
            const now = new Date();
            const diff = future - now;
            setDays(Math.floor( diff / (1000*60*60*24) ));
            setHours(Math.floor( diff / (1000*60*60) ));
            setMins(Math.floor( diff / (1000*60) ));
            setSecs(Math.floor( diff / 1000 ));
        }, 1000);
        return () => clearInterval(timer);
    }, []);
    
    return (
        <>
            <Timer days={days} hours={hours} mins={mins} secs={secs}/>
        </>
    )
}

If you need more help understanding hooks in React, I suggest you take a look at https://reactjs.org/docs/hooks-reference.html

Sign up to request clarification or add additional context in comments.

6 Comments

kindly update your code for component ( braces not closing properly ), giving me error
@coder Fixed. I forgot to close Countdown component function.
i am getting following error now "Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports "
sorry but your code is not working for me
@coder The code is a proof of concept and demonstration of how you can use hooks in React to display data to the DOM. It requires you to specify the date you want to calculate for the count as a prop to the <Countdown> component so this will not work as a simple copy-paste. I suggest you read the react documentation or watch some tutorials to improve your understanding of the framework. reactjs.org/docs/getting-started.html
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.