I have an object array, techstack
let techStack = [
{
name: "C",
image: "../Utils/C.png",
rating: 4,
},
{
name: "Java",
image: "../Utils/Java.png",
rating: 3.5,
},
{
name: "Python",
image: "../Utils/Python.png",
rating: 3,
},
{
name: "React Js",
image: "../Utils/React.png",
rating: 3.5,
},
{
name: "Bootstrap",
image: "../Utils/Bootstrap.svg",
rating: 3.5,
},
{
name: "Node.Js",
image: "../Utils/Node.png",
rating: 3,
},
{
name: "Flask",
image: "../Utils/Flask.png",
rating: 3,
},
{
name: "MySql",
image: "../Utils/SQL.png",
rating: 4,
},
]
And I am trying to render image’s source (<img src={} />
) with image
value from each object, like this:
<img src = {require(tech.image)} alt={tech.name} />
But while rendering, I get an error saying Cannot find module '../Utils/C.png'
. But when I use the same string separately (like src={require("../Utils/C.png")}
) the image is being rendered without any error. Why is this happening and how can I solve it.
I have used Material UI components.
Here is the JSX element
{techStack.map((tech, id) => (
<Grid key={id} item xs={6} md={3} my={4}>
<div>
<Tooltip title={tech.name}>
<img
src={require(tech.image)}
alt={tech.name}
style={{ marginBottom: "2%" }}
width={sizeBreak ? "50px" : "100px"}/>
</Tooltip>
<div>
<Rating
readOnly
value={tech.rating}
precision={0.5}/>
</div>
</div>
</Grid>
))}
2
Answers
The difference is first one is compiled as a variable not a path to the image but the second one is a path that the compiler will check.
I suggest an easy way. import images first and use this
src={tech.image}
the problem is the resulting artifact is not the same as your sources. webpack(or your other bundler) doesn’t handle pictures correctly as it can’t statically understand what should be bundled and how from the code above. To fix that, I would propose to put
require
call in the array instead of in the componentthis way webpack would bundle C.png correctly