Monday, 23 March 2020

What is ReactJS Component API?

 There are three methods to be explained in the React Component API
  • setState()
  • forceUpdate()
  • ReactDOM.findDOMNode()
Instead of a React Component are created internally in React when rendering. These instances are reused in subsequent renders and can be accessed in your component methods as this.

Set State

setState() method is used for updating the state of the component. State method is useful to add the changes to the original state but it will not replace the state.

import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
this.setStateHandler = this.setStateHandler.bind(this);
};
setStateHandler() {
var item = "setState..."
var myArray = this.state.data;
myArray.push(item)
this.setState({data: myArray})
};
render() {
return (
<div>
<button onClick = {this.setStateHandler}>SET STATE</button>
<h4>State Array: {this.state.data}</h4>
</div>
);
}
}
export default App;

The method starts with an empty array and each time we click the button, state will be updated. The result of the above example is rendered as:

ReactJS Component API

Force Update

Use forceUpdate() method, to update the component manually.
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;

The above example illustrates that the random number will be updated every time on clicking the button.

ReactJS Component API

Find Dom Node

ReactDOM.findDOMNode() method is used for DOM manipulation.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 below example illustrates the color of myDIv element is changed to green on clicking the button.

ReactJS Component API


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

No comments:

Post a Comment