I made a quick app.js file in react which shows me if the number is prime or not every 1s to infinity through the console.log , rn I wanna make it to render in the browser itself ” in the home page of mine I mean ” instead of console.log , any ideas?
import {useInterval} from "../hooks/use-interval"; let num = 0 export default function Task1Prime() { const isPrime = num => { for(let i = 2; i < num; i++) if(num % i === 0) return num+" isnt prime number"; return num+ " is prime number"; } useInterval(function (){ console.log(isPrime(num++)); },1000) return ( <div className="task"> </div> ); } ```
Advertisement
Answer
import {useInterval} from "../hooks/use-interval"; import {useState} from "react"; let num = 0 export default function Task1Prime() { const isPrime = num => { for(let i = 2; i < num; i++) if(num % i === 0) return num+" isnt prime number"; return num+ " is prime number"; } const [isNumPrime, setIsNumPrime] = useState(isPrime(num)) useInterval(function (){ setIsNumPrime(isPrime(num++)); },1000) return ( <div className="task"> { isNumPrime } </div> ); }
Use a state variable isNumPrime and just update it with the function and it’ll automatically change the element on the page.