0

I have multiple state variable in my component. Is there a way to iterate through all the state variable using for loop to get their value?

class AreaCalculator extends React.Component{

 constructor(props){
        super(props);
        this.state={Area1 : 'success',
                    Area2 : 'failure',
                    Area3 : 'success',
                    Area4 : 'failure',
                    Area5 : 'success',
                    Area6 : 'success',
                    Area7 : 'success',
                    Area8 : 'failure'
                    }
    }

    componentDidMount(){

    //Adding a for loop to print the value of state variable
    for(var i=0; i< this.state.length(); i++){
       
    //console log state variable value
    
     
    }
}
madhav koirala
  • 225
  • 3
  • 19
  • See the answers to the [linked question](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object), although if they're really `Area1`, `Area2`, etc., it seems like an array would be a better choice... :-) – T.J. Crowder Apr 05 '21 at 16:08
  • Unless your code knows about the property names (put area1 content here, put area5 content there) they aren't very useful and you should use an array instead. – James Apr 05 '21 at 16:12

0 Answers0