2
votes

I am new in React , I was following the course of React. And the code as follow appeared issue like "TypeError: Cannot read property 'map' of undefined"; Can anyone tell what's going on ? Thank you so much!

import React, { Component } from 'react'

const ListGroup = props => {
    const {items,textProperty,valueProperty} = props;
    return ( 
      <ul className="list-group">
          {items.map(item =>(
         <li key={item[valueProperty]} className="list-group-item">
             {item[textProperty]}
         </li>
          ))}
          
      </ul>
     );
}
 
export default ListGroup;
3
That means that the items object hasn't been set (undefined reference).John

3 Answers

1
votes

Your items object is undefined at the start. Just add a null check:

const ListGroup = props => {
    const {items,textProperty,valueProperty} = props;
    return ( 
      <ul className="list-group">
          {items && items.map(item =>(
               <li key={item[valueProperty]} className="list-group-item">
                 {item[textProperty]}
               </li>
          ))}
          
      </ul>
     );
}
2
votes

You didn't seem to pass items prop to ListGroup:

<ListGroup items=[] />

Alternatively, you can assign a default value to items:

const {items = [],textProperty,valueProperty} = props;

Or use elvis operator:

items?.map(item => {})
1
votes

You can use operate chaining, change your code to:

const ListGroup = props => {
    const {items,textProperty,valueProperty} = props;
    return ( 
      <ul className="list-group">

          { items?.map(item =>(
               <li key={item[valueProperty]} className="list-group-item">
                 {item[textProperty]}
               </li>
          ))}
          
      </ul>
     );
}
```