How can I build a time that changes every second on React.js?!

almuhannad1

Almuhannad_01

Posted on September 3, 2022

How can I build a time that changes every second on React.js?!

--> 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);


Enter fullscreen mode Exit fullscreen mode

4) update function time:



function updatetime() {
    const newtime = new Date().toLocaleTimeString();
    setTime(newtime);
  }


Enter fullscreen mode Exit fullscreen mode

5) Program output to the user:



return(
    <div>
      <h1>{time}</h1>
    </div>
);


Enter fullscreen mode Exit fullscreen mode

Final file will be šŸŽˆ:

Image description

Image description

šŸ˜
Thank you..

šŸ’– šŸ’Ŗ šŸ™… šŸš©
almuhannad1
Almuhannad_01

Posted on September 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related