How to display image read from json file in react js?

Sometimes, We want to display the image from json content in React Component.

The related posts:

Let’s have employee.json located in reactapplication/src/employee.json

[
  {
    "id": "1",
    "title": "Developer",
    "firstName": "John",
    "lastName": "Eric",
    "salary": 5000,
    "path": "/assets/imgs/employee/john.jpg"
  },
  {
    "id": "2",
    "title": "Tester",
    "firstName": "Andrew",
    "lastName": "Johnson",
    "salary": 6000,
    "path": "/assets/imgs/employee/andrew.jpg"
  }
]

Display image from the url given in a json file in react application

Let’s create a react component that contains the following things

  • import json file using import with a given path of json fil

    e

  • It read json file content as a string into a variable.

  • variable read and iterate records using map() function.

  • create an img tag with src value is record path using javascript expression

Here is an example code

import React, { Component } from "react";
import employee from "./employee.json";
class LocalFileRead extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        {employee.map((record, i) => (
          <div key={i}>
            <img src={record.path} />
            {record.id} - {record.firstName} {record.firstName}
          </div>
        ))}
      </div>
    );
  }
}

export default LocalFileRead;