I have a javascript Time function inside my React App component and everything is working well. But the main issue is I needed my seconds to keep on counting instead of standing static until the page is refresh.
Have tried several attempts but still not working. What I have presently is attached below.
My code is here below.
App.js
import React, { Component } from 'react'
export class App extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
function getDateTime() {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth()+1;
let day = now.getDate();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
if(month.toString().length === 1) {
month = '0'+month;
}
if(day.toString().length === 1) {
day = '0'+day;
}
if(hour.toString().length === 1) {
hour = '0'+hour;
}
if(minute.toString().length === 1) {
minute = '0'+minute;
}
if(second.toString().length === 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
return(
<div>
{<h2>The time is {getDateTime()}</h2>}
</div>
)}
}
export default App
Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);