State Change in Class Component in React JS Step by Step

 A state change in a class component is given below.

Step 1: Create a class component. A shortcut key to create a class component is rcc. Must install ES7 + React/Redux..

ES7 Icon

Step 2: Create a constructor of that class. The constructor is the most important. Without a constructor, the class component cannot change the state. The shortcut key to create a constructor is rconst.


Step 3: Assign a variable inside this.state like age. This is the place to assign multiple varibales here. State (Age) is changing by IncrementAge and DecrementAge function. Both buttons are disabled with the ternary operation.


Structure Flow

Finally: Output in browser-

Output



Code 👇
StateInClassComponent.js

import React, { Component } from 'react'

export default class StateInClassComponent extends Component { // Short cut key = rcc

    constructor(props) { // Short cut key = rconst
      super(props)
     
      this.state = {
          age : 0
      }
    }

    DecrementAge = () =>{  // Decrement Method Changing the state
        this.setState({
            age : this.state.age - 1
        })
    }

    IncrementAge = () => { // Increment Method Changing the state
        this.setState({
            age : this.state.age +1
        })
    }

  render() {
    const {age} = this.state
    return (
      <div>
        <h5>Age : {age}</h5>
        <button type='button' onClick={this.IncrementAge} disabled={age === 10 ?true: false}>+</button>
        <button type='button' onClick={this.DecrementAge} disabled={age === 0 ? true : false}>-</button>
      </div>
    )
  }

}



App.js

import React, { Component } from 'react';
import StateInClassComponent from './components/StateInClassComponent/StateInClassComponent.js';

export default class App extends Component {
  render() {
    return (
      <div>
        <h4>State use in Class Component</h4>
        <StateInClassComponent />
      </div>
    )
  }
}


Post a Comment

0 Comments