0

I am going to take a list of movies and show them. Each movie has a unique value called id, and I want to use it as a key.
But An error occurs : index.js:1 Warning: Each child in a list should have a unique "key" prop.

--- Skip ---

const Movie = ({
  movies,
  loading,
  nameSearch,
  setNameSearch,
}: MovieProps) => {
  let filterdMovieList: MovieType[] = [...movies];
  if (nameSearch) {
    filterdMovieList.sort();
    filterdMovieList = filterdMovieList.filter((movie: MovieType) => {
      return (
        movie.title.toLowerCase().indexOf(nameSearch) > -1 ||
        movie.title.toUpperCase().indexOf(nameSearch) > -1
      );
    });
  }
  return (
    <div className="movie">
      <MovieSearch setNameSearch={setNameSearch} nameSearch={nameSearch} />
      <div className="movie-container">
        {filterdMovieList.map((movie: MovieType) => {
          {
            console.log(movie.id);
          }
          return <MovieList movie={movie} key={movie.id.toString()} />;
        })}
        {loading && <MovieLoading />}
      </div>
    </div>
  );
};

export default Movie;

I don't understand this error.
And When I logged, the result likes this. enter image description here

It is rendered twice because I changed the state in the parent component's useEffect.

Sh031224
  • 769
  • 1
  • 7
  • 20
  • The IDs are not unique, they are all repeated twice, is that because of multiple rendering cycles? I suggest you make the key prop a combination of the ID and the index of the movie in the array. – M0nst3R Jul 24 '20 at 09:55
  • 1
    Are you sure debugger means this class? It looks like it is inside MovieList, not Movie: Log:`"in Fragment created by MovieList"` and `"Check render method of 'MovieList'"` – Jax-p Jul 24 '20 at 09:55
  • In fact, there was an error in the map used in the MovieList. Thank you so much – Sh031224 Jul 24 '20 at 10:03

1 Answers1

1

Your usage of Key in that map looks ok.

The error you have screenshotted says it is in another component, MovieList, that has Fragments without unique keys. Go take a look at that file instead.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22