I'm attempting to list queried posts in the DOM using Gatsby. The small snippet below should suffice because the Graphql query is correctly fetching data. This snippet is within the component, which is also rendering correctly. I'm new to Gatsby and React, and I hope I'm missing something pretty basic.
<div className="container">
Hello! // Renders
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
Hello! // Does not render
<p>{newsItem.context.id}</p> // Does not render
})}
</div>
CodePudding user response:
You've used curly braces, so this is how you return component from map function.
{newsItems.map(newsItem => {
console.log(newsItem.context.id); // Logs each news item id to console correctly
return (
<>
Hello!
<p>{newsItem.context.id}</p>
</>
)
})}
Haven't tried this, but it should work. This also only works if newsItems
contains values. React Fragments <>...</>
were used because return must only return single component. You could also use <div>...</div>
instead of fragment.
Try this.