Rendering the Image Field

The Image field allows content writers to upload an image that can be configured with size constraints and responsive image views.

Before Reading

This page assumes that you have retrieved your content and stored it in a variable named document

Retrieve the image url & alt text

The easiest way to render an image is to retrieve and add the image url and alt text to image elements.

Here is an example that retrieves the url and alt text from an Image field with the API ID of illustration.

Copy
<img src={document.data.illustration.url} alt={document.data.illustration.alt} />

Get an image view

It's easy to get the url for an image and any of its views. The following shows how to retrieve the image url for the main view as well as its tablet and mobile views. In this case, the Image field has an API ID of responsive_image, and it assumes that your have stored your document content in a state variable named "document".

Copy
render() {
  if (this.state.document) {
    const document = this.state.document;

    const mainView = document.data.responsive_image;
    const tabletView = document.data.responsive_image.tablet;
    const mobileView = document.data.responsive_image.mobile;

    return (
      <picture>
        <source media="(max-width: 400px)" srcSet={mobileView.url} />
        <source media="(max-width: 900px)" srcSet={tabletView.url} />
        <source srcSet={mainView.url} />
        <img src={mainView.url} alt={mainView.alt} />
      </picture>
    );
  } else {
    return null;
  }
}

If you added an alt text or copyright text value to your image, you retrieve them as shown below. Here the Image field has the API ID of image.

Copy
const image = document.data.image

const imageUrl = image.url // url
const imageAlt = image.alt // alt

The following shows how to retrieve the alt text for a responsive image view. Note that the alt text will be the same for all views.

Copy
const mobileView = document.data.image.mobile

const mobileUrl = mobileView.url // mobile image url
const mobileAlt = mobileView.alt // mobile image alt

Get the image Width & Height

Here's how to retrieve the main image's width or height. Here the Image field has the API ID of featured_image.

Copy
const image = document.data.featured_image

const imageWidth = image.dimensions.width // image width
const imageHeight = image.dimensions.height // image height

Here is how to retrieve the width and height for a responsive image view.

Copy
const mobileImage = document.data.featured_image.mobile;

const mobileWidth = mobileImage.dimensions.width // mobile image width
const mobileHeight = mobileImage.dimensions.height // mobile image height