#How to use getImage with "widths" property in a React component
3 messages · Page 1 of 1 (latest)
Sure, you can definitely take advantage of Astro's getImage() function and the <Picture /> component to create responsive images that load different sizes based on the viewport width. Here's a step-by-step guide on how you can achieve this:
- First, you need to import the
getImage()function fromastro:assetsin your Astro component. This function allows you to generate different image sizes.
--- import { getImage } from "astro:assets";---
Source (https://docs.astro.build/en/recipes/build-custom-img-component/)
- Define your responsive images by calling the
getImage()function with your desired properties. You can specify different widths for different viewport sizes.
---import type { ImageMetadata } from "astro";import { getImage } from "astro:assets";
interface Props { mobileImgUrl: string | ImageMetadata; desktopImgUrl: string | ImageMetadata; alt: string;}
const { mobileImgUrl, desktopImgUrl, alt } = Astro.props;
const mobileImg = await getImage({ src: mobileImgUrl, format: "webp", width: 200, height: 200,});
const desktopImg = await getImage({ src: desktopImgUrl, format: "webp", width: 800, height: 200,});---
Source (https://docs.astro.build/en/recipes/build-custom-img-component/)
- Then, you can use the
<Picture />component to generate a<picture>element with multiple<source>elements. This allows the browser to choose the best image to display based on the viewport width.
---
import { Picture } from 'astro:assets';
import myImage from './my-image.jpg';
---
<Picture src={myImage} formats={['avif', 'webp']} alt="My super image in multiple formats!" />
Source (https://astro.build/blog/astro-330/)
Please note that the <Picture /> component takes all the same props as the Image component, including the new densities and widths properties.
Also, keep in mind that Astro's <Image /> and <Picture /> components work in .astro and .mdx files only. In React (.jsx) components, you should use standard JSX image syntax (<img />). Astro will not optimize these images, but you can install and use NPM packages for more flexibility. Source (https://docs.astro.build/en/guides/migrate-to-astro/from-gatsby/)