ReactJS - Component API


Advertisements


In this tutorial we will explain React component API. We will show you three methods: setState(), forceUpdate and ReactDOM.findDOMNode(). In new ES6 classes we have to manually bind this. You will see in examples below that we are using this.method.bind(this).

Set State

setState() method is used for updating the state of the component. This method will not replace the state but only add changes to original 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;

We started with empty array. Every time we click the button, the state will be updated. If we click it five times, we will get the following output.

React Component API Set State

Force Update

Sometimes you want to update the component manually. You can achieve this by using forceUpdate() method.

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;

We are setting random number that will be updated every time the button is clicked.

React Component API Force Update

Find Dom Node

For DOM manipulation, we can use ReactDOM.findDOMNode() method. 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 color of myDiv element is changed to green, once the button is clicked.

React Component API Find Dom Node

NOTE

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



Advertisements