user3335796
user3335796

Reputation: 1237

Button Click in array map using react js

I was going through couple of examples from official website. I found below example which sets the button values based on click.

example

With reference to above example, I used array map and tried to set button value of perticular button.

class Toggle extends React.Component {
constructor(props) {
  super(props);
  this.state = {isToggleOn: true};
 // This binding is necessary to make `this` work in the callback
  this.handleClick = this.handleClick.bind(this);
 }

 handleClick() {
  this.setState(prevState => ({
    isToggleOn: !prevState.isToggleOn
  }));
}
render() {
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <button key={number} onClick={this.handleClick}>
    {this.state.isToggleOn ? 'ON' : 'OFF'}
  </button>
);
return (
  {listItems}
);
}
}

ReactDOM.render(
 <Toggle />,
 document.getElementById('root')
);

As per above modified code, I've given unique key but still I could see all buttons are setting at a time.

Why its happening? How I can achieve its result. Why I'm not able to set unique identification?

Upvotes: 4

Views: 10453

Answers (1)

Soumya Sharma
Soumya Sharma

Reputation: 31

    class Toggle extends React.Component {
constructor(props) {
  super(props);
  this.state = {isToggleOn: [true,true,false,true,true]};
 // This binding is necessary to make `this` work in the callback
  this.handleClick = this.handleClick.bind(this);
 }

 handleClick(index) {
 var testData=this.state.isToggleOn;

 if(this.state.isToggleOn[index]==true)
    testData[index]=false;
 else
    testData[index]=true;

this.setState({isToggleOn:testData});
}
render() {
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number,index) =>
  <button key={number} onClick={this.handleClick.bind(this,index)}>
    {this.state.isToggleOn[index] ? 'ON' : 'OFF'}
  </button>
);

return (
<div>
  {listItems}
  </div>
);
}
}

ReactDOM.render(
 <Toggle />,
 document.getElementById('root')
);

Upvotes: 2

Related Questions