react js-tutorial

React Component API

ReactJS component is a top-level API. It makes the code completely individual and reusable in the application. 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.

  • setState()
  • forceUpdate()
  • findDOMNode()

setState()

The component’s state can be updated using this method. The state is not always promptly replaced by this method. Instead, it only augments the initial state. It is the main technique used to alter the user interface (UI) in response to server responses and event handlers.

Syntax

this.stateState(object newState[, function callback]);  

In the above syntax, there is an optional callback function which is executed once setState() is completed and the component is re-rendered.

Example

import React, { Component } from 'react';  
import PropTypes from 'prop-types';  
class App extends React.Component {  
   constructor() {  
      super();        
      this.state = {  
          msg: "Welcome to JavaTpoint"  
      };      
      this.updateSetState = this.updateSetState.bind(this);  
   }  
   updateSetState() {  
       this.setState({  
          msg:"Its a best ReactJS tutorial"  
       });  
   }  
   render() {  
      return (  
         <div>  
             <h1>{this.state.msg}</h1>  
             <button onClick = {this.updateSetState}>SET STATE</button>  
         </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.

Syntax

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 (  
         <div>  
             <h1>Example to generate random number</h1>  
             <h3>Random number: {Math.random()}</h3>  
             <button onClick = {this.forceUpdateState}>ForceUpdate</button>  
         </div>  
      );  
   }  
}  
export default App;  

Output

Each time when you click on ForceUpdate button, it will generate the random number. It can be shown in the below image

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.