Component API: ReactJS goes through a development process. Initially, the components are written based on the old JavaScript syntax. Until 0.14, ReactJS version, it was transfered to use the JavaScript according to the ES6 standard. Many old Component APIs are deprecated or removed to conform to the new standard. It includes various methods for:-
- Creating elements
- Transforming elements
- Fragments
Here, we are going to explain the three most important methods available in the React component API.
1. setState()
2. forceUpdate()
3. findDOMNode()
setState()
setState() method is used to update the state of the component. This method will not replace the state, but only add changes to the original state. It is a primary method that is used to update the user interface(UI) in response to event handlers and server responses.
App.js
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.slice();
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;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));
forceUpdate()
This method allows us to update the component manually.
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.slice();
myArray.push(item);
this.setState({data: myArray})
};
render() {
return (
findDomNode()
For DOM manipulation, we can use ReactDOM.findDOMNode() method. First we need to import react-dom.
class Fruits extends React.Component {
doFind() {
// Find root Node of this Component
var node = ReactDOM.findDOMNode(this);
node.style.border = "1px solid red";
}
render() {
return (
<ul>
<li>Apple</li>
<li>Guava</li>
<li>Watermelon</li>
<li>
<button onClick={() => this.doFind()}>Find Root Node</button>
<h3 id = "myDivOne">JTP-NODE1</h3>
<h3 id = "myDivTwo">JTP-NODE2</h3>
</li>
</ul>
);
}
}
// Render
ReactDOM.render(<Fruits />, document.getElementById("fruits1"));
Once you click on the button, the color of the node gets changed. It can be shown in the below screen.
Read more
React create-react app
State vs Props in React
ReactJS Constructor() Method