B L Λ C K
B L Λ C K

Reputation: 642

How do I import svg images with passed names via props in Astro?

I have a component where I assign title, description and image from a prop. I am using a JSON Array to iterate over to create multiple instance of this component and add images.

I have two problems while using images in Astro -

Problem 1 : Astro ignores image on build when using images with direct path without import syntax.

<img 
    class="spec-logo linear-gradient"
    src={'../assets/specifications/'+imgname+'.svg'} 
    alt={title}/>

So I read other SF posts and came to know that import syntax mitigate this problem.

Now I have other problems because I dont know how to dynamically import the images using import syntax

Problem 2 : Inline import syntax isn't working as explained here -

I have used img tag

<img 
  class="spec-logo linear-gradient"
  src={import('../assets/specifications/battery.svg')} <---
  alt={title}/>

  error -- 
  'Promise<typeof import("*.svg")>' is not assignable to type 'string'

Another solution I tried was this -

<Fragment set:html={import('../assets/specifications/battery.svg?raw')} />

This is rendering [object object]

The third and final solution I tired is this -

<svg class="w-6 h-6">
            <use xlink:href={import('../assets/specifications/battery.svg') + '#icon-id'}></use>
          </svg>

None of the above is working -

Upvotes: 1

Views: 952

Answers (1)

B L Λ C K
B L Λ C K

Reputation: 642

The solution I found after reading this blog is below -

interface Props {
    title: string;
    description: string;
    imgsrc: string;
} 

const { title, description, imgsrc } = Astro.props as Props;
const { default: innerHTML } = await import(`../assets/specifications/${imgsrc}.svg?raw`);


<span class="card-title">{title}</span> 
<span class="card-value linear-gradient">{description}</span>
<Fragment set:html={innerHTML} class="spec-logo"/>

Edit 1: It seems it worked fine but as soon as I build the project and checked the preview, all these images were missing. The problem still persists as these images are not getting include on build.

Edit 2: I think build wasn't done properly. After closing the IDE and rebuilding fixed the issue.

Upvotes: 0

Related Questions