Joshua
Joshua

Reputation: 41

Error when importing image dynamically: "Error: Cannot find module './asset/<imageName>.jpg'"

I am currently trying to load local images based on the path given by JSON data. The data is passed in to my component as props. Since the component is dynamically created based on the JSON data, I can't import the images. So I tried to "require" them, but I get an error saying,

"Error: Cannot find module './asset/.jpg' "

The image loads just fine if I manually import them, so I believe the path is formatted correctly.

Why am I getting error? How do I fix it?

import React from "react";
import ReactDOM from "react-dom";

function Cell (props){

    return (
    <tr>
        <th>1</th>
        <th><img src= {require(props.image)} /></th>
        <th><div className = "name">{props.name}</div></th>
        <th>
            <a className = "upVote">🔺</a>
            <a className = "downVote">🔻</a>
        </th>
        <th className = "count">{props.count}</th>
    </tr>
    );
}

export default Cell;

Upvotes: 0

Views: 1636

Answers (1)

BHAR4T
BHAR4T

Reputation: 334

If your image is in public folder then you can directly write:

<img src={props.image} />

OR

<img src="abc.png" />

There is no need to use require for it.

You can also import image like this if images and component is in same directory:

import abc from "./abc.jpeg";

<img src={abc} />

OR

<img src={require("./abc.jpeg")} />

Upvotes: 1

Related Questions