I have a react app which displays posts by using the WP Rest APi.
To display, I'm using map() to loop through the posts.
{posts.map((articles, i) => {
return (
<Post
key={posts[i].id}
id={posts[i].id}
title = {posts[i].title.rendered}
link = {posts[i].link}
img = {posts[i]._embedded['wp:featuredmedia'][0].source_url}
category = {posts[i].categories}
/>
)
})
}
Because the first post doesn't have a featured image, the component breaks and I get the following console error message
Uncaught TypeError: Cannot read properties of undefined (reading '0')
If I remove the img prop, there are no issues, everything displays correctly.
Do I need to wrap the img prop into a conditional? Can you please advise on how I can fix the issue?
Any help much appreciated.