Site icon Tutorial

Component Lifecycle

Each component has several “lifecycle methods” that you can override to run code at particular times in the process.

Mounting

These methods are called in the following order when an instance of a component is being created and inserted into the DOM:

Updating

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

Unmounting

This method is called when a component is being removed from the DOM:

Error Handling

These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

Force Update

Sometimes we might want to update the component manually. This can be achieved using the forceUpdate() method.

import React from ‘react’;

class App extends React.Component {

constructor() {

super();

this.forceUpdateHandler = this.forceUpdateHandler.bind(this);

};

forceUpdateHandler() {

this.forceUpdate();

};

render() {

return (

<div>

<button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button>

<h4>Random number: {Math.random()}</h4>

</div>

);

}

}

export default App;

We are setting a random number that will be updated every time the button is clicked.

Find DOM Node

For DOM manipulation, we can use ReactDOM.findDOMNode() method. First we need to import react-dom.

import React from ‘react’;

import ReactDOM from ‘react-dom’;

class App extends React.Component {

constructor() {

super();

this.findDomNodeHandler = this.findDomNodeHandler.bind(this);

};

findDomNodeHandler() {

var myDiv = document.getElementById(‘myDiv’);

ReactDOM.findDOMNode(myDiv).style.color = ‘green’;

}

render() {

return (

<div>

<button onClick = {this.findDomNodeHandler}>FIND DOME NODE</button>

<div id = “myDiv”>NODE</div>

</div>

);

}

}

export default App;

The color of myDiv element changes to green, once the button is clicked.

Since the 0.14 update, most of the older component API methods are deprecated or removed to accommodate ES6.

Exit mobile version