Sunday, August 12, 2018

ComponentDidMount example

The componentDidMount life-cycle method is the last lifecycle method executed in the component mounting phase. componentDidMount() is invoked immediately after the component is mounted.

The following example uses ComponentDidMount() to alter the state property "title", in this example we will not make any api calls, but will use setTimeout() to inject a 1 second delay in setting the state. The state change will re-trigger render() and the updated state will be displayed in the browser.

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloComponentDidMount extends Component {
  constructor(props) {
    super(props);
    this.state = {
title: ""
};
  }

  componentDidMount(){
    setTimeout(() => {
      this.setState({
        title: 'Hello ComponentDidMount'
      })
    }, 1000)
  }

  render() {
return (
  <div>
{this.state.title}
  </div>
);
  }
}

ReactDOM.render(<HelloComponentDidMount />, document.getElementById('app'));


Search Flipkart Products:
Flipkart.com

No comments: