How can I build a time that changes every second on React.js?!
Almuhannad_01
Posted on September 3, 2022
--> The technicals which will use in this program (React.js, React Hooks - useState).
The program..
1) add:
import React, {useState} from "react";
2) add function which name the same for the file e.g// App
function App() {
setInterval(sayHi, 1000) --> This function prints sayHi every second, but you will add setInterval(updatetime, 1000);
const now = new Date(); --> This is the object for the Date. For example// you can get the hour when you write const now = new Date ().getHours();, but here you want full-time (( hour: min: sec AM/PM )) for that, will use:
const now = new Date().toLocaleTimeString();
3) add hooks:
const [time,setTime] = useState(now);
4) update function time:
function updatetime() {
const newtime = new Date().toLocaleTimeString();
setTime(newtime);
}
5) Program output to the user:
return(
<div>
<h1>{time}</h1>
</div>
);
Final file will be š:
š
Thank you..
Posted on September 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.