#Passing image src and alt as props

3 messages · Page 1 of 1 (latest)

sweet gazelle
#

How can I pass an src and alt attribute to the <Image> component as a prop?

echo jayBOT
#

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

#

You can pass the src and alt attributes to the <Image /> component as props in Astro. Here's an example of how you can do it:

---import { Image } from 'astro:assets';import myImage from "../assets/my_image.png";---
<!-- `alt` is mandatory on the Image component --><Image src={myImage} alt="A description of my image." />

In the above example, myImage is an imported image file and "A description of my image." is the alt text. Both are passed as props to the <Image /> component.

You can also create a custom component and pass the src and alt as props to it. Here's an example:

---import { Image } from "astro:assets";interface Props { src: ImageMetadata; alt: string;}const { src, alt } = Astro.props;---<Image src={src} alt={alt} />

In this example, a custom component MarkdocImage.astro is created which accepts src and alt as props and passes them to the <Image /> component.

Remember, the src attribute requires a specific format depending on where your image file is located. For local images in src/, you must also import the image using a relative file path or configure and use an import alias. For images in the public/ folder, use the image’s file path relative to the public folder. For remote images, use the image’s full URL as the property value.

Sources:


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