Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 330
athenatechie Avatar asked Jan 15 '18 15:01

athenatechie


People also ask

Can I use key as a prop in React?

Keys are internal to React and can not be accessed from inside of the component like props.

Do you need to add key property on Reactjs elements?

Almost every React application displays an array list of some kind using the method map. And React tells us that for each element of that list that we return for rendering, we must provide a unique key prop.

What is the React key prop?

React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.

Is key required in React?

Keys help React identify which items have changed (added/removed/re-ordered). To give a unique identity to every element inside the array, a key is required.


1 Answers

You are rendering an array of elements, so React needs a key prop (1) 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> ); 
like image 186
kLabz Avatar answered Sep 20 '22 13:09

kLabz