TyForHelpDude
TyForHelpDude

Reputation: 5001

insist on "Each child in an array or iterator should have a unique "key" prop"

I know what does it means and solved this problem many times with setting unique id to child items but this time it still throws the same exception and I couldn't understand why

here is the code;

    render() {
     question.Choices = this.appState.question.Choices.map((value, index) => {
            if (typeof value == "string")
              return (<SQcomponent index={index} value={question.Number + "-" + index} text={value} checkedHandler={this.choiceChecked} />)
    })
    return (<div> {question.Choices} </div>)
  }
}


    class SQcomponent extends Component {
      constructor(props) {
        super(props)
      }
      render() {
        return (<div key={this.props.index} className="checkbox checkbox-circle">
          <input id={this.props.index} name={this.props.index} type="checkbox" value={this.props.value} />
          <label htmlFor={this.props.index}>
            {this.props.text}
          </label>
        </div>)
      }
    }

when I start the application it works fine but this messege annoying me; enter image description here

Upvotes: 0

Views: 407

Answers (1)

ovation22
ovation22

Reputation: 731

You need to put the key on the component in your map:

    render() {
     question.Choices = this.appState.question.Choices.map((value, index) => {
            if (typeof value == "string")
              return (<SQcomponent key={index} index={index} value={question.Number + "-" + index} text={value} checkedHandler={this.choiceChecked} />)
    })
    return (<div> {question.Choices} </div>)
  }
}


Though, you should use a value other than index for your key.

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:

https://facebook.github.io/react/docs/lists-and-keys.html

Upvotes: 2

Related Questions