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;
Keys are internal to React and can not be accessed from inside of the component like props.
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.
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.
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.
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> );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With