ReactJS - Component API

Today we will explain React Component API. It makes the code thoroughly individual and reusable in the application.


setState() method is utilized to update the state of the component. This method will not supersede the state, but only integrate changes to the pristine state.

Example

import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
message: "Greetings from knowledgefactory"
};
this.updateSetState = this.updateSetState.bind(this);
}
updateSetState() {
this.setState({
message: "Best of luck"
});
}
render() {
return (
<div>
<div class="panel panel-success">
<div class="panel-heading">{this.state.message}</div>
</div>

<button type="button" class="btn btn-success" onClick=
                       {this.updateSetState}>SET STATE</button>
</div>
);
}
}
export default App;

Output:


When you click on the SET STATE button, you will visually perceive the following screen with the updated message.


forceUpdate()

This method sanctions us to update the component manually.

Example

import React from 'react';
class App extends React.Component {
constructor() {
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler() {
this.forceUpdate();
};
render() {
return (
<div>
<button type="button" class="btn btn-danger" onClick =
                {this.forceUpdateHandler}>Force update</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;

Output:

Each time when we click on the Force update button, it will engender an arbitrary number.


findDOMNode()

For DOM manipulation, we require to utilize ReactDOM.findDOMNode() method. This method sanctions us to find or access the underlying DOM node.

Example

import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.findDomNodeHandler = this.findDomNodeHandler.bind(this);
};
findDomNodeHandler() {
var yourDiv = document.getElementById('yourDiv');
ReactDOM.findDOMNode(yourDiv).style.color = 'purple';
}
render() {
return (
<div>
<button type="button" class="btn btn-danger" onClick=
                {this.findDomNodeHandler}>FIND DOME JAVASCRIPT</button>
<h1 id="yourDiv">Javascript</h1>
</div>
);
}
}
export default App;

Output:

The color of the Div element changes to purple, once the button is clicked.


CRUD

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete