Home > Net >  React js component update
React js component update

Time:12-30


import React from 'react'
class Clock extends React. Component{
    constructor(){
        super();
        this. State={
            date: new Date()
        }
    }
    render(){
        return(
            <>
            <h1>{this. state. date. toLocaleTimeString()}</h1>
            </>
        )
    }
}
export default Clock;

import Clock from './Clock';
const root=ReactDOM. createRoot(document. getElementById("root"));
const clock=()=> {
    console.log("hi");
    root.render(<Clock/>)
}
setInterval(() => {
    clock();
}, 1000);

after every one second we are calling clock function in index.js , so it means after every one second rendering the element also, but it is not updating in browser after every one second. In console "hi" is printing it means my clock function is running after every one second. What I am missing in concept?

CodePudding user response:

React changes the rendering only if the state changes. So to change the state you have to set it. You can try this:

  componentDidMount() {
      this.setState({ date: new Date() })
   }

CodePudding user response:

You can implement the clock this way:

import React from "react";

class Clock extends React.Component {
  constructor() {
    super();
    this.state = {
      date: new Date()
    };
  }

  componentDidMount() {
    this.intervalID = setInterval(() => this.updateClock(), 1000);
  }

  //This section clears setInterval by calling intervalID so as to optimise memory
  componentWillUnmount() {
    clearInterval(this.intervalID);
  }

  //This function set the state of the time to a new time
  updateClock() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <>
        <h1>{this.state.date.toLocaleTimeString()}</h1>
      </>
    );
  }
}
export default Clock;

Live demo here: https://codesandbox.io/s/clock-react-class-comp-4wjbj0

  • Related