I'm getting the error "each child in a list should have a unique 'key' prop" error, but I'm confused because I'm attempting to set the key to a unique ID, and it seems like it's not working. I'm using the imdbID as the key, which should be a primary key value (unique and stable). Is my syntax wrong, or what am I doing that's incorrect here ?
import React from 'react';
import "./movie.css";
class Movie extends React.Component {
render() {
const {Title, Poster, Year, imdbID} = this.props;
return (
<div className="movie" key={imdbID} id={imdbID}>
<div className="title-year">
<h1 className="title">{Title}</h1>
<h2 className="year">{Year}</h2>
</div>
<div className="poster">
<img src={Poster} alt="my movie poster"/>
</div>
</div>
)
}
}
export default Movie;
And here is the code that's inserting <Movie...> into the application (app.js):
render() {
return (
<div className="App">
<header className="App-header">
<Search handleSendRequest={this.sendRequest}/>
<div className="response">
{
this.state.movies && this.state.movies.length ? this.state.movies.map((movie) => {
return <Movie {...movie}/>
})
: null
}
</div>
</header>
</div>
);
}
CodePudding user response:
Add a key
attribute to your Movie tags and set a unique value. As below
{
this.state.movies && this.state.movies.length ? this.state.movies.map((movie, index) => {
return <Movie key={movie.imdbID} { ...movie
}
/>
}) :
null
}
CodePudding user response:
You need the key on <Movie/>
itself:
{
this.state.movies && this.state.movies.length ? this.state.movies.map((movie) => {
return <Movie key="HERE" {...movie}/>
})
: null
}
In particular, you need a key every time you iterate over an object. In this case you are iterating over this.state.movies
.
You do not need the key inside Movie's render function, where you placed it, because you are not iterating over any object at that time.
CodePudding user response:
The 'key' prop should be inserted at the <Movie/>
component, not in the div inside it.