Advertisement
shopnilSS

Use of Set state in React

May 6th, 2021
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from 'react'
  2. let i = 0
  3. class Random extends Component {
  4.     constructor(props) {
  5.         super(props)
  6.    
  7.         this.state = {
  8.              elementIndex : 0
  9.         }
  10.     }
  11.    
  12.     hello = () => {
  13.         let arr = ["1st", "2nd", "3rd", "4rth", "5th", "6th"]
  14.        
  15.         this.setState({
  16.             elementIndex: arr[i]
  17.         })
  18.         if(i > arr.length - 1){
  19.             this.setState ({
  20.                 elementIndex: "Array is full"
  21.             })
  22.         }
  23.         i++
  24.     }
  25.     render() {
  26.         return (
  27.             <div>
  28.                 <h1>Array Element: {this.state.elementIndex}</h1>
  29.                 <button onClick = {this.hello}>Click me</button>
  30.             </div>
  31.         )
  32.     }
  33. }
  34.  
  35. export default Random
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement