Component API in ReactJS

React Component API A ReactJS application is known to be a multi-component application. Each component of the ReactJS application is reusable and is responsible for outputting a small, reusable piece of HTML code. React Component API includes various methods for creating elements, transforming elements and fragments to make the code completely individual and reusable in the application and is thus a top-level API. The three most important methods of the React component API are setState() method, forceUpdate() method and findDOMNode() method.

The setState() method: The setState() method is a primary method which is used to set or update a state of the component and it also triggers UI updates on calling. It does not replace the state immediately, but only adds changes to the original state. It is also used to update the user interface(UI) in response to event handlers and server responses.

Syntax:

this.stateState(object newState, function_callback);  

Parameters: function_callback: It is an optional parameter which is executed once setState() is completed and the component is re-rendered.

Example: App.js:

import React, { Component } from 'react';  
import PropTypes from 'prop-types';  
class App extends React.Component {  
constructor() {  
super();        
this.state = {  
message: "Hello World"  
};      
this.updateSetState = this.updateSetState.bind(this);  
}  
updateSetState() {  
this.setState({  
message:"It is a beautiful day."  
});  
}  
render() {  
return (  

{this.state.message}

); } } export default App;

Main.js:

import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  
ReactDOM.render(, document.getElementById('app'));  

Output 1: Before the button click. import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { constructor() { super(); this.findDomNodeHandlerONE = this.findDomNodeHandlerONE.bind(this); this.findDomNodeHandlerTWO = this.findDomNodeHandlerTWO.bind(this); }; findDomNodeHandlerONE() { var X = document.getElementById('XOne'); ReactDOM.findDOMNode(XOne).style.color = 'crimson’; } findDomNodeHandlerTWO() { var X = document.getElementById('XTwo'); ReactDOM.findDOMNode(XTwo).style.color = 'purple’; } render() { return (

Find DOM Node

NODE1

NODE2

); } } export default App;

Output 1: Before the button click. Component.forceUpdate (callback);

Example: App.js:

import React, { Component } from 'react';  
class App extends React.Component {  
constructor() {  
super();            
this.forceUpdateState = this.forceUpdateState.bind(this);  
}  
forceUpdateState() {  
this.forceUpdate();  
};  
render() {  
return (  

Random number

{Math.random()}

); } } export default App;

Output 1: Before the button click. error

fb-share-icon
Content Protection by DMCA.com