5 April 2020

Live Clock in react js

  • Create Components folder under src folder
  • Add LiveClockUpdate.js file and add below Code
import React, { Component } from "react";

class LiveClockUpdate extends Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h2>{this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default LiveClockUpdate;
  • Open App.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import LiveClockUpdate from "./components/LiveClockUpdate";

function App() {
return (
<div className="App">
<LiveClockUpdate />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:


No comments:

Post a Comment