Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Best practices for using image sizes in React projects with Sanity.io

3 replies
Last updated: May 21, 2020
Hi people,For those of you who use
imageUrlFor(buildImageObj(node.mainImage))...
how do you ensure to download a proper size of image for the current view port?

I have a code like

<img 
    src={imageUrlFor(buildImageObj(node.mainImage))
                      .auto('format')
                      .width(1000)
                      .url()} 
/>
Instead of
1000
, what do you do? Do you use JavaScript to get window width and calculate the width of image you want to get? Or is there any other recommended practice?
May 21, 2020, 1:41 PM
Hey
user S
I’ve used something like that on a project
 <picture>
        <img
          style={{ width: "100%" }}
          srcSet={`
            ${urlFor(node.asset).width(320)} 320w,
            ${urlFor(node.asset).width(480)} 480w,
            ${urlFor(node.asset).width(800)} 800w
          `}
          sizes={`
            (max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px
          `}
          src={urlFor(asset)}
        />
      </picture>
May 21, 2020, 3:39 PM
user T
Oh, I didn't think of that. I'm not very good with images 😅 Thanks for the tip!
May 21, 2020, 4:14 PM
I got this snippet straight from a codesandbox, but I can’t find the link 🤔 I tend to prefer this solution to GatsbyImage.
May 21, 2020, 4:19 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?