Learn React JS

Update State using setState Method in ReactJS


You will learn how to update or modify the state in ReactJS. SetState() method is used to change the states.

this.state = {
tutorial_name : “ReactJS”
}

Above example showing tutorial_name has a value ReactJS. This value will be updated as given below program. It will update ReactJS to ReactJS Tutorial

this.setState({tutorial_name:”ReactJS Tutorial”});

Let us understand with an example

Tutorial.js

import React, { Component } from "react";

class Tutorial extends Component{

    constructor(props){
        super(props);
        this.state = {
            tutorial_name : 'ReactJS'
        };
    }

    updateState = () => {
        this.setState({tutorial_name:'ReactJS Tutorial'});
    }

    render(){
        return(
            <div>
                <h1>Learn Update State using setState Method in {this.state.tutorial_name}</h1>
                <button onClick={this.updateState}>Click Here</button>
            </div>
        );
    }
}

export default Tutorial;

index.js

import React from "react";
import ReactDOM from "react-dom";

import Tutorial from './Tutorial';

//Rendering component...
ReactDOM.render(<Tutorial />, document.getElementById("root"));