What is ReactJS Component API?

In this tutorial we are reading about What is ReactJS Component API?”.
There are three methods to be explained in the React Component API
  • setState()
  • forceUpdate()
  • ReactDOM.findDOMNode()
Instead of a React Component are created internally in React when rendering.These instances are reused in subsequent renders,and can be accessed in your component methods as this.

Set State

setState() method is used for updating the state of the component. State method is useful to add the changes to the original state but it will not replace the state.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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>SET STATE</button>
<h4>State Array: {this.state.data}</h4>
</div>
);
}
}
export default App;
The method starts with an empty array and each time we click the button, state will be updated. The result of the above example is rendered as:
What is ReactJS Component API?

Force Update

Use forceUpdate() method, to update the component manually.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';

class App extends React.Component {
constructor() {
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler() {
this.forceUpdate();
};
render() {
return (
<div><button>FORCE UPDATE</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;
The above example illustrates that the random number will be updated every time on clicking the button.
What is ReactJS Component API?

Find Dom Node

ReactDOM.findDOMNode() method is used for DOM manipulation.First we need to import react-dom.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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>FIND DOME NODE</button>
<div id="myDiv">NODE</div>
</div>
);
}
}
export default App;
The below example illustrate the color of myDIv element is changed to green on clicking the button.
What is ReactJS Component API?
So in this tutorial we have read about “What is ReactJS Component API?”.

Comments

Popular posts from this blog

Java Number Class

Java Character Class

What are Web Resources in Microsoft Dynamics 365?