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
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> ); };
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.
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 { }).