#How can I pass a static URL of an image to an href element in an astro component?

3 messages · Page 1 of 1 (latest)

paper egret
#

Hey Everyone,

I am stumped on a problem:

I have this component and i want to pass in the static url to the href element, so that the images opens in full res on click. How can I pass in the static URL? I think I am missing some important concepts... If someone can explain to me, how this would ideally be done, I am very thankful 🙃

...

interface Props {
    margin_top?: string;
    width?: string;
    height?: string;
    aspectratio?: string;
    loading?: 'eager' | 'lazy';
    to?: string;
    altText: string;
    imagePath: string;
    onhover_imagePath?: string;
    viewtransition_name?: string;
    
  };
  
// Get component props from Astro.props
const { margin_top = '0px', to, width = "100%", height = 'auto', aspectratio = 'auto', loading = 'lazy',altText = "Joshua Binswanger Scientific Illustration", imagePath, onhover_imagePath, viewtransition_name } = Astro.props;

//Import all image paths to check against the passed in strings
const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/**/*.{jpeg,jpg,png,gif,webp}');

// Check if the image exists and assign it to myImage
if (!images[imagePath]) throw new Error(`"${imagePath}" does not exist in glob: "src/assets/**/*.{jpeg,jpg,png,gif,webp}"`);
const myImage = images[imagePath]();
const imageUrl = myImage.src; // Use the actual image URL

// If the `to` prop is passed, it will override the imageUrl
const linkUrl = to ?? imageUrl;

---
<div id="Image">
    <a href={linkUrl}>
      <Picture  
      src={myImage} 
      formats={['avif', 'webp']}
      width={myImage.width / 3}
      densities={[1, 1.5, 2, 2.5, 3]}
      alt={altText} 
      loading={loading}
      style={`
      width: ${width}; 
      height: ${height}; 
      object-fit: cover; 
      aspect-ratio: ${aspectratio}
      `}>
    </a> 
</div> ```
lament wing
#

So what is the result of running the above code? What's the problem?

paper egret
#

Hey, sorry for not posting the error message. I found out that I did not pass in the default property in the src={myImage}. When I changed it to {myImage.default} it worked! Reading the docs more thouroughly and taking a break in between helps a lot, I found out!