Home >>ReactJS Tutorial >ReactJS Component API

ReactJS Component API

ReactJS Component API

Setstate

The method setState() is used to update component state. This method does not replace the state, but will only apply changes to the 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 = "hello Phptpoint..."
      var myArray = this.state.data.slice();
     myArray.push(item);
      this.setState({data: myArray})
   };
   render() {
      return (
         <div>
            <button onClick = {this.setStateHandler}>CLICK ME TO SET STATE</button>
            <h4>State Array: {this.state.data}</h4>           
         </div>
      );
   }
}
export default App;

we will get the following output.

Output

reactjs Component API

Force Update

We will want to update the part manually, sometimes. This can be done with the method forceUpdate().

we will get the following output.

Output

reactjs Component API

Find Dom Node

We can use the method ReactDOM.findDOMNode() for manipulation of the DOM. We need to first import a 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}>CLICK ME </button>
            <div id = "myDiv">NODE</div>
         </div>
      );
   }
}
export default App;

Output

reactjs Component API