I'm trying to call an image through a dummy dataset in React.
I am using the below:
<li>
<img src={testimonials[0].image} alt={testimonials[0].name}/>
</li>
And my data looks:
const testimonials = [
{
name: "Julia Cameron",
title: "Creative Director, VISA",
image: `${require("../assets/image.jpg")}`,
quote:
"It's all good. I was amazed at the quality of the Design. We've seen amazing results already."
},
{
name: "Mark Jacobs",
title: "Tech Lead, Google",
image: `${require("../assets/image2.jpg")}`,
quote:
"The rebranding has really helped our business. Definitely worth the investment."
},
{
name: "Lisa Bearings",
title: "Brand Coordinator, Facebook",
image: `${require("../assets/image3.jpg")}`,
quote:
"The service was excellent. Absolutely wonderful! A complete redesign did it for us."
}
];
However this does not render the img but the alt tag.
I am able to import the img directly with the source, so the path is correct:
import img from '../assets/image.jpg'
Can anyone confirm what i'm doing incorrectly? Obviously it's within the specific line:
image: `${require("../assets/image.jpg")}`,
CodePudding user response:
This isn't the best solution but you can just import those images in the same file as the Array above, like
import image1 from "../assets/image1";
then inside the array it could be
image:{image1}
CodePudding user response:
You are passing the source in String literal. The following statement will return a string which is invalid.
`${require("../assets/image.jpg")}`
Either you need to pass the Image object by import it directly. Or either place the images in the /public/assets
folder and pass the string there. Any of the following will work for you.
import img from '../assets/image.jpg';
<img src={img} alt="pic" />
OR
<img src="/assets/image.jpg" alt="pic" />
CodePudding user response:
just use the name you imported in your data instead of string literal
import Image1 from "../assets/image.jpg"
import Image2 from "../assets/image2.jpg"
import Image3 from "../assets/image3.jpg"
const testimonials = [
{
name: "Julia Cameron",
title: "Creative Director, VISA",
image: Image1,
quote:
"It's all good. I was amazed at the quality of the Design. We've seen amazing results already."
},
{
name: "Mark Jacobs",
title: "Tech Lead, Google",
image: Image2,
quote:
"The rebranding has really helped our business. Definitely worth the investment."
},
{
name: "Lisa Bearings",
title: "Brand Coordinator, Facebook",
image: Image3,
quote:
"The service was excellent. Absolutely wonderful! A complete redesign did it for us."
}
];