reactjsomdbapi

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;

Solution

  • 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