Components

Image Component

The Image component is recommended for use when rendering files of type image from your assets in Contento. It is designed to enable easy manipulation of images using our Image Optimization API and convert appropriate images to webp for fasting loading times.

Attributes

asset: Takes an object of type AssetData from the Contento JavaScript SDK that is then used within the function to access the asset.url and the asset.description. This is a required attribute.

apiParams: Takes a string and appends it as parameters to the end of your asset.url after a ? This will apply the requested parameters from the Image Optimization API. This is an optional attribute.

className: Takes a string and uses it as the React className attribute available for css styling and applies it on the <img /> and <picture> tags. This is an optional attribute.

noWebp: Takes a boolean and if true outputs a standard <img/> tag rather than a <picture> tag as webp. If you do not want your image asset to be converted to webp then you can set this attribute to true. This is an optional attribute which defaults to false from undefined if no boolean is passed in.

Code Examples

The Image Component

We recommend adding the following code to an Image.tsx file in app > components.

import { AssetData } from '@gocontento/client/lib/types'

export default function Image({
  asset,
  apiParams,
  className,
  noWebp,
}: {
  asset: AssetData
  apiParams?: string
  className?: string
  noWebp?: boolean
}) {
  return (
    <>
      {noWebp && (
        <img
          src={apiParams ? asset.url + '?' + apiParams : asset.url}
          alt={asset.description ?? ''}
          className={className}
        />
      )}
      {!noWebp && (
        <picture className={className}>
          <source
            srcSet={
              apiParams
                ? asset.url + '?' + apiParams + '&fm=webp'
                : asset.url + '?fm=webp'
            }
            type="image/webp"
          />
          <img
            src={apiParams ? asset.url + '?' + apiParams : asset.url}
            alt={asset.description ?? ''}
          />
        </picture>
      )}
    </>
  )
}

Implementation

To use the Image component, import it at the top of the desired file and make sure the asset attribute is getting data from the correct field. This is an example of how the asset data can be accessed for an asset field named image. Here we also show example parameters for the apiParams attribute and className attribute.

import Image from '@/components/Image'

<Image
        asset={block.fields.image.assets[0].asset}
        apiParams="fit=crop&w=750&dpr=2"
        className="max-w-[750px]"
/>
Hollie Duncan

Written by Hollie Duncan

Updated

Previous
Block Matcher