lorenzodejong / next-sanity-image

Utility for using responsive images hosted on the Sanity.io CDN with the Next.js image component.
MIT License
148 stars 19 forks source link

Best way to filter empty image fields? #27

Closed michael-odonovan closed 2 years ago

michael-odonovan commented 2 years ago

Hi, Previously I have been using the Sanity UrlBuilder and filtering empty fields from there:

import imageUrlBuilder from '@sanity/image-url'
import sanityClient from '../client'
import BlockContent from '@sanity/block-content-to-react'

export default function Blurb({ blurb }) {
  const builder = imageUrlBuilder(sanityClient)

  function urlFor(source) {
    if (!source) {
      return
    } else {
      return builder.image(source)
    }
  }

  return (
    <>
      <img src={urlFor(blurb.mainImage)} />
      <h1>{blurb.heading}</h1>
      <div><BlockContent blocks={blurb.body} /></div>
    </>
  )
}

However I'm having a lot of trouble working out how to do this using the next-sanity plugin. Sorry for this, I am quite new.

michael-odonovan commented 2 years ago

Sorry I am being really dumb today. Simple solution:

return (
      { (blurb.mainImage) && <Image {...imageProps} /> }
}

of course feel free to delete as this is just my inexperience. regards