I am new to React, and I'm trying to output a table containing the information of users. But Eslint is keep giving me the following error:
[eslint] Missing "key" prop for element in iterator [react/jsx-key]
I am not sure if I did this properly, but I have assigned a unique ID number for each person in the user list, but not sure why the error is persistent.
So in my PeopleCard.js I have the following:
import React from "react"; import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from "reactstrap"; import PropTypes from "prop-types"; class PeopleCard extends React.Component { static propTypes = { person: PropTypes.object, id: PropTypes.number, name: PropTypes.string, company: PropTypes.string, description: PropTypes.string }; render() { return ( <div> <Card> <CardImg top width="100%" src="" alt="Card image cap" /> <CardBody> <CardTitle>{this.props.person.name}</CardTitle> <CardSubtitle>{this.props.person.company}</CardSubtitle> <CardText>{this.props.person.description}</CardText> <Button>Button</Button> </CardBody> </Card> </div> ); } } export default PeopleCard; And in my MainArea.js, I have the following:
import React from "react"; import { Container, Row, Col } from "reactstrap"; import PeopleCard from "./PeopleCard"; class MainArea extends React.Component { constructor() { super(); this.state = { people: [ { id: 1, name: "John", company: "Some Company, Inc", description: "Met at a party." }, { id: 2, name: "Mary", company: "Some Company, Inc", description: "Met at a party." }, { id: 3, name: "Jane", company: "Some Company, Inc", description: "Met at a party." } ] }; } render() { let peopleCard = this.state.people.map(person => { return ( <Col sm="4"> <PeopleCard key={person.id} person={person} /> </Col> ); }); return ( <Container fluid> <Row>{peopleCard}</Row> </Container> ); } } export default MainArea; The following line is throwing the error, and I cannot figure out why:
<Col sm="4"> <PeopleCard key={person.id} person={person} /> </Col> How can I prevent this error from appearing?
2 Answers
You should put the key on the outer element:
const peopleCard = this.state.people.map(person => ( <Col key={person.id} sm="4"> <PeopleCard person={person} /> </Col> )); 4sometime it still give issue if your two key values get match so better use this way. render() { let peopleCard = this.state.people.map((person, index) => { return ( <Col sm="4" key={`${person.id}+${index}`}> <PeopleCard key={person.id} person={person} /> </Col> ); }); return ( <Container fluid> <Row>{peopleCard}</Row> </Container> ); }
were no two loop will have same id with index which can make key value different.