4

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?

1
  • 3
    this.state.isToggleOn is only a single value. You need a toggle state for each button. It doesn't have anything to do with key prop. Commented Mar 7, 2017 at 13:25

1 Answer 1

2
    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')
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.