ReactJS - Component API

Today we will explain React Component API. It makes the code thoroughly individual and reusable in the application.



Here, we are going to explicate the three most paramount methods available in the React component API.
  1. setState()
  2. forceUpdate()
  3. findDOMNode()

setState()

setState() method is utilized to update the state of the component. This method will not supersede the state, but only integrate changes to the pristine state.

Example

import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
message: "Greetings from knowledgefactory"
};
this.updateSetState = this.updateSetState.bind(this);
}
updateSetState() {
this.setState({
message: "Best of luck"
});
}
render() {
return (
<div>
<div class="panel panel-success">
<div class="panel-heading">{this.state.message}</div>
</div>

<button type="button" class="btn btn-success" onClick=
                       {this.updateSetState}>SET STATE</button>
</div>
);
}
}
export default App;

Output:


When you click on the SET STATE button, you will visually perceive the following screen with the updated message.


forceUpdate()

This method sanctions us to update the component manually.

Example

import React from 'react';
class App extends React.Component {
constructor() {
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler() {
this.forceUpdate();
};
render() {
return (
<div>
<button type="button" class="btn btn-danger" onClick =
                {this.forceUpdateHandler}>Force update</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;

Output:

Each time when we click on the Force update button, it will engender an arbitrary number.


findDOMNode()

For DOM manipulation, we require to utilize ReactDOM.findDOMNode() method. This method sanctions us to find or access the underlying DOM node.

Example

import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.findDomNodeHandler = this.findDomNodeHandler.bind(this);
};
findDomNodeHandler() {
var yourDiv = document.getElementById('yourDiv');
ReactDOM.findDOMNode(yourDiv).style.color = 'purple';
}
render() {
return (
<div>
<button type="button" class="btn btn-danger" onClick=
                {this.findDomNodeHandler}>FIND DOME JAVASCRIPT</button>
<h1 id="yourDiv">Javascript</h1>
</div>
);
}
}
export default App;

Output:

The color of the Div element changes to purple, once the button is clicked.


More...

Comments