TypeError: Cannot read property 'map' of undefined" React

Viewed 721

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;
4 Answers

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 => {})

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>
     );
}

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>
     );
}
```

I'm taking the same course. Make sure that you have passed the right props to ListGroup in Movies class just like that:

<ListGroup
                items={this.state.genres}
                textProperty="name"
                valueProperty="_id"
                onItemSelect={this.handleGenreSelect}
/> 

Regards!

Related