React - how to print an array contained in array

React - how to print an array contained in array
0

#1

It’s working as expected but it doesn’t give an error when trying to print the array
What’s a better way to print the array I have in state?

{this.state.op} that how I am printing it but it doesn’t show anything

class App extends React.Component {
constructor(props) {
        super(props);
        this.state = {
            items: myData,
            op:[]
        };
    }

 handleClick(element) {
     console.log('The button was clicked.');
console.log(element);

this.state.op.push(element);   
console.log(this.state.op);

  }


  render () { 
  	return (
    	<div>
      {
    	  Object.keys(this.state.items).map(key => {
        	return <button onClick={this.handleClick.bind(this,this.state.items[key])}> {key} - {this.state.items[key]}</button>
        })
      }

       {this.state.op} //here
    	</div>
    )
}
}

export default App;

#2

Just like the code above it, you need to map over the array and return some jsx. Don’t forget to add a key attribute to the jsx with a unique value.


#3

Never, ever, directly mutate data in the state. React would never know that the state changed when you do that, so it can’t render the changes. Always use this.setState if you need to change the state. This is how you might do it:

this.setState({
  op: this.state.op.concat(element);
})

After calling this.setState, React will trigger another render, with the updated state.

I think console.log would work just fine though

But this part confuses me:


#4

Should I add the key attribute to the button?


#5

Yes. You need to add a key attribute whenever you create some jsx using an iterator like map. It’s so React has a unique reference to it so it can change the DOM accurately. For example if you start removing DOM elements that don’t have a unique key, the wrong ones might get removed.