Updating the State of Class-Based Components

To update the state of a class based component we will be using the given setState method. Class based component can directly access the states using this keyword.

Example: This example update the state of component in the React Class Components.

Javascript




// Filename - App.js
 
import React, { Component } from 'react';
 
class App extends Component {
    constructor() {
        super()
        this.state = {
            text: 'Welcome to w3wiki'
        }
    }
 
    goPremium() {
        this.setState({
            text: 'Subscription successful'
        })
    }
    render() {
        return (
            <div>
                <h1>{this.state.text}</h1>
                <button onClick={() => this.goPremium()}>
                    Go Premium
                </button>
            </div>
        );
    }
}
 
export default App;


Step to run the application: Open the terminal and type the following command. 

npm start

Output: This output will be visible on the localhost:3000

How to update the State of a component in ReactJS ?

To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content.

Similar Reads

Prerequisites:

NPM & Node.js React JS React State React JS Class Components React JS Functional Components...

Approach:

The State is an instance of a React Component that can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. The state of a component can be updated during its lifetime....

Steps to Create React Application:

Step 1: Create a React application using the following command:...

Approach 1: Updating the State of Class-Based Components

To update the state of a class based component we will be using the given setState method. Class based component can directly access the states using this keyword....

Approach 2: Updating the State of functional Components

...

Contact Us