[SOLVED] Missing "key" prop for element. (ReactJS and TypeScript)

Issue

I am using below code for reactJS and typescript. While executing the commands I get below error.

I also added the import statement
import ‘bootstrap/dist/css/bootstrap.min.css’;
in Index.tsx.

Is there a way to fix this issue?

npm start

client/src/Results.tsx
(32,21): Missing "key" prop for element.

The file is as below “Results.tsx”

import * as React from 'react';
 class Results extends React.Component<{}, any> {

constructor(props: any) {
    super(props);

    this.state = {
        topics: [],
        isLoading: false
    };
}

componentDidMount() {
    this.setState({isLoading: true});

    fetch('http://localhost:8080/topics')
        .then(response => response.json())
        .then(data => this.setState({topics: data, isLoading: false}));
}

render() {
    const {topics, isLoading} = this.state;

    if (isLoading) {
        return <p>Loading...</p>;
    }

    return (
        <div>
            <h2>Results List</h2>
            {topics.map((topic: any) =>
                <div className="panel panel-default">
                    <div className="panel-heading" key={topic.id}>{topic.name}</div>
                    <div className="panel-body" key={topic.id}>{topic.description}</div>
                </div>
            )}
        </div>
    );
}
}

export default Results;

Solution

You are rendering an array of elements, so React needs a key prop (see react docs) to identify elements and optimize things.

Add key={topic.id} to your jsx:

return (
  <div>
    <h2>Results List</h2>
    {topics.map((topic: any) =>
      <div className="panel panel-default" key={topic.id}>
        <div className="panel-heading">{topic.name}</div>
        <div className="panel-body">{topic.description}</div>
      </div>
    )}
  </div>
);

Answered By – kLabz

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *