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.
Contact Us