React Class Component - Rendering (Mounting/Unmounting)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Class Component

1 - About

Advertising

3 - Method

In a class component, mounting and unmounting are methods:

  • componentDidMount: Runs after the component output has been rendered to the DOM
  • componentWillUnmount
  • componentDidUpdate

In a function component, there is no lifecycle methods.

4 - Example

  • A component with state using the lifecycle functions componentWillUnmount and componentDidMount.
class LifeCycle extends React.Component {
 
  //  Since Clock needs to display the current time, the constructor initializes this.state
  constructor(props) {
    super(props);
    this.state = {count:0}
    this.handleClick = this.handleClick.bind(this);
  }
 
  // When the render output is inserted in the DOM, React calls the componentDidMount() lifecycle hook. 
  componentDidMount() {
    console.log("Mounted - The Lifecyle was added (mounted)");
  }
 
  //  Called if the component is ever removed from the DOM
  componentWillUnmount() {
    console.log("UnMounted - The Lifecyle component was removed (unmounted)");
  }
 
  //  Called if the component is updated from the DOM
  componentDidUpdate() {
    console.log("Updated - The Lifecyle component was updated "+this.state.count+" times");
  }
 
  handleClick(){
     this.setState({count:this.state.count+1});
  }
 
  // What should be displayed on the screen. 
  render() {
    return (
      <div>
        <p>Hello from the Lifecyle component</p>
        <button type="button" onClick={this.handleClick}>Update the component</button>
      </div>
    );
  }
}
class App extends React.Component {
 
  //  Since Clock needs to display the current time, the constructor initializes this.state
  constructor(props) {
    super(props);
    this.state = {isToggleOn: false};
    this.handleClick = this.handleClick.bind(this);
  }
 
  handleClick(e) {
   this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
 
  // What should be displayed on the screen. 
  render() {
    let cycle = null;
    if (this.state.isToggleOn) {
      cycle = <LifeCycle/>;
    } 
    return (
      <div>
        <h1>Mount/Unmount/Update demo</h1>
        <button type="button" onClick={this.handleClick}>{this.state.isToggleOn ? 'Unmount the lifecycle component' : 'Mount the lifecycle component'}</button>
        {cycle}
      </div>
    );
  }
}
  • The classic Render to start the rendering. When <Lifecycle /> is passed to ReactDOM.render(), React calls the constructor of the Clock component, then calls the Clock component's render() method.
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>

Advertising