coder
coder

Reputation: 9

How to use javascript/jquery in Reactjs

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>

Upvotes: 0

Views: 101

Answers (1)

Jack Ecuyer
Jack Ecuyer

Reputation: 165

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

Upvotes: 2

Related Questions