#How to use getImage with "widths" property in a React component

3 messages · Page 1 of 1 (latest)

sonic brookBOT
#

Hi @feral trench. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

  1. First, you need to import the getImage() function from astro:assets in 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/)

  1. 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/)

  1. 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 &lt;Picture /&gt; component takes all the same props as the Image component, including the new densities and widths properties.

Also, keep in mind that Astro's &lt;Image /&gt; and &lt;Picture /&gt; components work in .astro and .mdx files only. In React (.jsx) components, you should use standard JSX image syntax (&lt;img /&gt;). 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/)

I hope this helps! Let me know if you have any other questions.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: