How to get an image from the src folder dynamically through props in vite + react app

569 Views Asked by At
export default function Card(props) {
    return (
        <card>
            <img className={cardCss.card__img} src={`../assets/imgs/card/${props.img}`} alt="" />
            <div className={cardCss.card__stats}>
                <img className={cardCss.star} src={star} alt="" />
                <span className={cardCss.rating}>5.0
                </span>
                <span className={cardCss.gray}>(6) • </span>
                <span className={cardCss.gray}>USA</span>
            </div>
            <p className={cardCss.card__title}>
                Life lessons with Katie Zaferes
            </p>
            <p className={cardCss.card__pricing}>
            <span className={cardCss.bold}>From $136</span> / person
            </p>
        </card>
    );
}

Here I'm writing src={../assets/imgs/card/${props.img}} in the img tag. and


export default function App() {

  return (
    <div>
      <Nav />
      <Main />
      <Card 
          img = "img1.svg"
      />
    </div>
  );
}

This is how I'm giving the img property to the Card component. The path is correct. But it's not displaying the image. An in the console it's showing

img1.svg:1 GET http://localhost:5173/assets/imgs/card/img1.svg 404 (Not Found)

Please someone tell me how to solve this.

I tried writing the whole path in the src tag like

src="../assets/imgs/card/img1.svg".

But this also isn't working. It's again showing the same error in the console.

And the path is correct as I used the same path to import the image

import img1 from "../assets/imgs/card/img1.svg";

and in image tag src = {img1};

But I want src={../assets/imgs/card/${props.img}} this to work, so that I can dynamically import the image using props

2

There are 2 best solutions below

0
On

Remove the colon from the beginning, it should start with /

<img className={cardCss.card__img} src={`/assets/imgs/card/${props.img}`} alt="" />
0
On

first step is to check if the relative paths are right. check if the paths are right from where file is present.

you may also try with the following code

<img className={cardCss.card__img} src={"../assets/imgs/card/"+props.img} alt="" />

also check if the extenstions are right.