Im using this code for listing the posts
const PostList = () => {
const [posts, setPosts] = useState({});
const fetchPosts = async () => {
const res = await axios.get("http://localhost:4002/posts");
setPosts(res.data);
};
useEffect(() => {
fetchPosts();
}, []);
const renderedPosts = Object.values(posts).map((post) => {
return (
<div
className="card"
style={{ width: "30%", marginBottom: "20px" }}
key={post.id}
>
<div className="card-body" key={post.id}>
<h3>{post.title}</h3>
<CommentList comments={post.comments} />
<CommentCreate postId={post.id} />
</div>
</div>
);
});
return (
<div className="d-flex flex-row flex-wrap justify-content-between">
{renderedPosts}
</div>
);
};
export default PostList;
But im getting the error
Warning: Each child in a list should have a unique "key" prop.
Check the render method of PostList
. See https://reactjs.org/link/warning-keys for more information.
at div
at PostList (http://localhost:3000/static/js/bundle.js:441:76)
at div
at App
Please help
2
Answers
Render the component in this way.
As the warning states, each child needs to have a unique key. You assigned the same
key={post.id}
to both parent and childdiv
in yourrenderedPosts
component.The solution is to remove
key
property from the nesteddiv
: