简体   繁体   中英

How to render photos coming from Contentful in Gatsby

I have a model in contentful called Work that includes a lot of data and one of the fields is a 'Thumbnail' I managed to render all data successfully but the thumbnail.

the query:

{
    allContentfulWork(sort: { fields: publishDate, order: DESC }) {
      edges {
        node {
          thumbnail {
            file {
              url
            }
          }
          title
          slug
          fromDate(formatString: "MMMM Do, YYYY")
          toDate(formatString: "MMMM Do, YYYY")
          publishDate
          gallery {
          file {
            url
          }
        }
      }
    }
  }
}

my jsx:

<img src={edge.node.thumbnail.file.url} alt={edge.node.title} />

the error I get: TypeError: Cannot read property 'file' of null

I would like to know how to render it and also how to use gatsby images with it.

One of your "work" entries inside Contentful is missing a thumbnail. Either you didn't add it, or the entry didn't get published, or the asset got deleted.

In general, your code needs to handle this case because your content editors will sometimes delete links even though Contentful warns them not to. You should refactor your JSX like this:

{edge.node.thumbnail && <img src={edge.node.thumbnail.file.url} alt={edge.node.title} />}

This will only render the img tag if the thumbnail exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM