bradtraversy / next-crash-course

Project from my Next.js crash course on YouTube
429 stars 328 forks source link

ArticleList key prop #5

Open kmylo opened 3 years ago

kmylo commented 3 years ago

image

farisadlin commented 3 years ago

That was because you didn't put key on your articles.map so eslint marked your line of code. Just put the key in your map and you should be fine

import articleStyles from "../styles/Article.module.css";
import ArticleItem from "./ArticleItem";

const ArticleList = ({ articles }) => {
  return (
    <div className={articleStyles.grid}>
      {articles.map((article, key) => (
        <ArticleItem key={key} article={article} />
      ))}
    </div>
  );
};

export default ArticleList;
KarrarAlbuakaab commented 2 years ago

thanks farisadlin

YamatoDX commented 2 years ago

That was because you didn't put key on your articles.map so eslint marked your line of code. Just put the key in your map and you should be fine

import articleStyles from "../styles/Article.module.css";
import ArticleItem from "./ArticleItem";

const ArticleList = ({ articles }) => {
  return (
    <div className={articleStyles.grid}>
      {articles.map((article, key) => (
        <ArticleItem key={key} article={article} />
      ))}
    </div>
  );
};

export default ArticleList;

It is an anti-pattern to use index as key prop

xgqfrms commented 2 years ago

if the item exists with a unique id, just use it first, and use the index as a fallback solution.

uid meanings the unique id


import articleStyles from "../styles/Article.module.css";
import ArticleItem from "./ArticleItem";

const ArticleList = ({ articles }) => {
  return (
    <div className={articleStyles.grid}>
      {articles.map((article, key) => (
        <ArticleItem key={article.uid || key} article={article} />
      ))}
    </div>
  );
};

export default ArticleList;