John_ny
John_ny

Reputation: 807

How to load the images from JSON object using react?

I have created the array of objects and i gave image path in that. I couldn't able to load the images from the array of objects using react and am getting an error like "module not found".I have stuck with this issue for past 2 days, kindly anyone help me out in fixing this issue or give me some suggestion for what to do next. I shared you the code snippet below:

    state = {
        data: [
          {
            id: 1,
            name: "Mattel Uno Playing Card Game",
            imagePath: "../images/lenovo-p50.jpg"
          },
          {
            id: 2,
            name: "Hot Wheels Car",
            imagePath: "../images/lenovo-p51.jfif"
          },
          {
            id: 3,
            name: "Centy Toys Ambassador Car",
            imagePath: "../images/lenovo-p50.jpg"
          }
        ]
      };

      render() {
        return (
          <div>
            <table>
              <thead>
                <tr>
                  <th>Item Name</th>
                  <th>Item images</th>
                </tr>
              </thead>
              <tbody>
                {this.state.data.map((ele, i) => {
                  return (
                    <tr key={ele.id}>
                      <td>{ele.name}</td>
                      <td>
                        <img src={require(ele.imagePath)} width="200" />
                      </td>
                    </tr>
                  );
                })}
                <tr />
              </tbody>
            </table>
          </div>
        );
      }

How to load the images from the array of objects in react?

Upvotes: 0

Views: 176

Answers (1)

Umair Farooq
Umair Farooq

Reputation: 1823

You don't need to add require in src. When relative path is used it will go the images availale in your server but when url is given image will be loaded. You can find more info here

When using src as /images/lenovo-p50.jpg it will convert to localhost:3000/images/lenovo-p50.jpg

Upvotes: 2

Related Questions