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..
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.
Finally: Output in browser-
Code 👇
StateInClassComponent.js
import React, { Component } from 'react'export default class StateInClassComponent extends Component { // Short cut key = rccconstructor(props) { // Short cut key = rconstsuper(props)this.state = {age : 0}}DecrementAge = () =>{ // Decrement Method Changing the statethis.setState({age : this.state.age - 1})}IncrementAge = () => { // Increment Method Changing the statethis.setState({age : this.state.age +1})}render() {const {age} = this.statereturn (<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>)}}
0 Comments