M.A.G
M.A.G

Reputation: 549

Warning: flattenChildren(...): Encountered two children with the same key, `false` in REACTJS

I am trying to create a list and make it clickable so that once i click on an item i get redirect to another page

here is the render method

 render() {
const quesItems = this.state.questions.map((question, i) => {
  return (
    <li key={this.props.account.id === question.expID}>
      <a href={`/ans/${question.id}`}> {question.description}</a>
    </li>
  );
});
return (
  <div>
    <h1> Answer the questions here!</h1>
    <ul>
      {quesItems}
    </ul>
  </div>
);

}

However i am getting the following warning when i click on any item on the list. How can i fix it?

index.js:2177 Warning: flattenChildren(...): Encountered two children with the same key, `false`. Child keys must be unique; when two children share a key, only the first child will be used.

Upvotes: 0

Views: 55

Answers (1)

trixn
trixn

Reputation: 16309

The expression this.props.account.id === question.expID returns a boolean value. The key prop should usually not be a boolean (there are only two distinct values). Probably quesItems contains multiple items whose expID does not equal this.props.account.id. All those will render with key={false} which is not allowed. The correct value for a key prop is probably just the question id;

EDIT: Based on the suggestion of @Colin I added the filtering logic. Also see Array.prototype.filter().

render() {
    const questions = this.state.questions.filter(question => question.expID === this.props.account.id)

    return (
        <div>
            <h1>Answer the questions here!</h1>
            <ul>
                {questions.map(({id, description}) => (
                    <li key={id}>
                        <a href={`/ans/${id}`}>{description}</a>
                    </li>
                ))}
            </ul>
        </div>
    );
}

Upvotes: 1

Related Questions