spreet
spreet

Reputation: 23

TypeError: Cannot read property 'map' of null Reactjs

Link to the TypeError Screenshot

The App was working fine yesterday. I deleted the project and cloned from Github.com. Still it won't work. Here's the link to the code: Link to the Github Project

import React from 'react';

function SearchMovies(props) {
  const FavoriteComponent = props.favoriteComponent;
  return (
    <>
      {props.movies.map((movie, index) => (
        <div>
          s<img src={movie.Poster} alt='movie'></img>
          <div onClick={() => props.handleFavoritesClick(movie)}>
            <FavoriteComponent />
          </div>
        </div>
      ))}
    </>
  );
}

export default SearchMovies;

Upvotes: -1

Views: 68

Answers (1)

Ketan Ramteke
Ketan Ramteke

Reputation: 10665

In your SearchMovies component try using null propagation to avoid that error.

{props.movies?.map((movie, index) => (...

import React from 'react';

function SearchMovies(props) {
  const FavoriteComponent = props.favoriteComponent;
  return (
    <>
      {props.movies?.map((movie, index) => (
        <div>
          s<img src={movie.Poster} alt='movie'></img>
          <div onClick={() => props.handleFavoritesClick(movie)}>
            <FavoriteComponent />
          </div>
        </div>
      ))}
    </>
  );
}

export default SearchMovies;

Working App after correction: Stackblitz

Upvotes: 1

Related Questions