import React from "react";
const ProjectCard = (props) => {
const {title , context, thumbnail, date, skillset, website} = props;
console.log(thumbnail == "../assets/project1.png") # renders to be true
return (
<section id="">
<div className="card" style={{width: '18rem'}}>
<img className="col-12" src={require('' + thumbnail)} alt=""/> # doesn't work
<img className="col-12" src={require("../assets/project1.png")} alt=""/> # works
<div className="card-body">
<h5 className="card-title">{title}</h5>
<p className="card-text">{date}</p>
</div>
</div>
</section>
)
}
export default ProjectCard;
I’m trying to build a portfolio website and currently I am making a project card to hold the images and text. I’m importing the properties from my parent component which passes the path of the image into a src but for some reason when I try to use the prop thumbnail it doesn’t work even when I concatenated but it works when I just have the path alone.
Can someone tell me why. Thank you so much
3
Answers
Actually when we use "require" is expects a static path.
So when you’re using
require("../assets/project1.png")
, it’s working because you’re providing a static path.On the other hand, when you’re using
require('' + thumbnail)
, it isn’t working becausethumbnail
is dynamic, it’s coming from theprops
.To pass the "thumbnail" dynamically, just ensure the image you’re importing, in parent component, are in the public directory.
Then you can simple pass the images as props.
Hope it helped!
The issue you’re facing is related to how webpack handles static assets. When you use
require
with a static string, webpack can correctly bundle the image file with your JavaScript. However, when you userequire
with a variable (likethumbnail
in your case), webpack doesn’t know at compile time what file you’re referring to, so it can’t correctly bundle the image.To solve this issue, you need to import the image in the parent component and pass it as a prop to the
ProjectCard
component. Here’s an example:And in your
ProjectCard
component, you can use thethumbnail
prop directly:Now, the webpack can correctly bundle the image because it knows what file you’re referring to at compile time.
Webpack handles static imports differently from variable imports. If you want to import files you can try this.
Top level import
then you can use it like