Build a custom image component
이 컨텐츠는 아직 번역되지 않았습니다.
Astro provides two built-in components that you can use to display and optimize your images. The <Picture>
component allows you to display responsive images and work with different formats and sizes. The <Image>
component will optimize your images and allow you to pass in different formats and quality properties.
When you need options that the <Picture>
and <Image>
components do not currently support, you can use the getImage()
function to create a custom component.
In this recipe, you will use the getImage()
function to create your own custom image component that displays different source images based on media queries.
Recipe
Section titled Recipe-
Create a new Astro component and import the
getImage()
function -
Create a new component for your custom image.
MyCustomComponent.astro
will receive threeprops
fromAstro.props
. ThemobileImgUrl
anddesktopImgUrl
props are used for creating your image at different viewport sizes. Thealt
prop is used for the image’s alt text. These props will be passed wherever you render your custom image components. Add the following imports and define the props that you will use in your component. You can also use TypeScript to type the props. -
Define each of your responsive images by calling the
getImage()
function with your desired properties. -
Create a
<picture>
element that generates asrcset
with your different images based on your desired media queries. -
Import and use
<MyCustomImageComponent />
in any.astro
file. Be sure to pass the necessary props for generating two different images at the different viewport sizes: