javascriptastrojs

Handle returning null from map method


I'm trying to handle a map method that get all my fields from a JSON query. Some of the fields I'm getting are empty which is fine, but when calling them I get an error saying "Cannot read properties of null".

So my idea was to put an if statement inside the map to check if the item is null and in that case don't return it at all. But I can't seem to get it to work and I'm unsure what I'm doing wrong.

This is how the code looks that doesn't work:

{
  peoplePosts.map((post) => (
    <h2>{post.title}</h2>
    <p>{post.content}</p>
    <p>{post.featuredImage.node.sourceUrl}</p>
  ))
}

Error message from this is: "Cannot read properties of null (reading 'node')"

And this is my solution which doesn't work either 😅

{
  peoplePosts.map((post) => (
    <h2>{post.title}</h2>
    <p>{post.content}</p>
    if (post.featuredImage.node.sourceUrl == null) {
      <p>Ouch</p>
    } else {
      <p>Yay</p>
    }
  ))
}

Error message from this is: "Expected ")" but found "if""


Solution

  • You need to use conditional (ternary) operators to render it properly

    {
      peoplePosts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
          {post.featuredImage ? (
            <p>Yay</p>
          ) : (
            <p>Ouch</p>
          )}
        </div>
      ))
    }