Pratik Dhumal
Pratik Dhumal

Reputation: 11

Error : Cannot read property 'map' of undefined React.JS

I'm following the react js tutorial, and I keep running into this issue

import React from "react";
import NewsCard from "../NewsCard/NewsCard";
const NewsCards = ({ articles }) => {
  return (
    <div>
      {articles.map((article, i) => {
        <NewsCard />;
      })}
    </div>
  );
};

export default NewsCards;

Upvotes: 0

Views: 104

Answers (4)

Gabe T
Gabe T

Reputation: 25

If you still need help, just like what the previous answers said, make sure that articles is initialized/defined by using the && operator to make that check. Also, based upon what you wrote, the map method is returning undefined since you specified a function body (using the function body bracket notation {} ) without a return statement. So instead write the map method like this:

<div>
{articles && articles.map((article, i) => <NewsCard />)}
</div> 

or like this:

<div>
{articles && articles.map((article, i) => {
   return <NewsCard />
})}
</div>

The first example has a implicit return since an arrow function is being used and a function body is not present (there are no function body brackets { }).

Upvotes: 1

Dimitar
Dimitar

Reputation: 1180

This means that the articles prop is undefined.

There are several ways to solve this. The first and easiest way is by implementing the following logic:

{articles?.length ? articles.map((article, i) => <NewsCard />) : "There are no articles here."}

Another way to solve this is by implementing React proptypes - you can read about this here.

Third and "hardest" (but probably best) way to solve this is by using a static type checking tool. Flow comes to mind, but you can use TypeScript too.

Upvotes: 0

Chuck
Chuck

Reputation: 804

Seems like your articles does not have default value as []. You can change as follow. And you should give key attribute when using map function.

const NewsCards = ({ articles }) => {
  const data = articles ? articles : []
  return (
    <div>
      {data.map((article, i) => {
        <NewsCard key={article.id}/>;
      })}
    </div>
  );
};

Upvotes: 1

Jacki
Jacki

Reputation: 672

Probably articles is not initialized when you try to map throught it. Try this:

{articles?.map((article, i) => {
        <NewsCard />;
      })}

OR

{articles && articles.map((article, i) => {
        <NewsCard />;
      })}
    </div>

That way you will first make sure if articles exist

Upvotes: 0

Related Questions