How to display the content of a JSON file in React with an example

This tutorial shows how to display json files located in the public folder in react component example.

REST data is read from API and displayed to UI. This tutorial reads from a static folder and displays

In my application, the employee.json file is located in a location: react/src/employee.json.

[
  {
    "id": "1",
    "title": "Developer",
    "firstName": "John",
    "lastName": "Eric",
    "salary": 5000
  },
  {
    "id": "2",
    "title": "Tester",
    "firstName": "Andrew",
    "lastName": "Johnson",
    "salary": 6000
  }
]

How to read Raw json content from a local external json file in react component

This example prints JSON content read from json file located in React application.

In the react component, Import json file as given below

import employee from "./employee.json";

JSOn content is read as a string to the employee variable pass employee variable to JSON.stringify to print the json string in the browser.

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

  render() {
    return <div>{JSON.stringify(employee)}</div>;
  }
}

export default LocalFileRead;

Output:

[
  {
    "id": "1",
    "title": "Developer",
    "firstName": "John",
    "lastName": "Eric",
    "salary": 5000
  },
  {
    "id": "2",
    "title": "Tester",
    "firstName": "Andrew",
    "lastName": "Johnson",
    "salary": 6000
  }
]

How to display local external json files in react component

We have seen how to print raw json strings read from a local file in react component.

In this example, Read the json data and print it to the table or inline elements.

In React Component,

  • Import json file with the given path and json content is stored to a variable with the name given in the import
  • In render, iterate imported variable and use map to iterate data and print the data using javascript expression
  • map method iterates to iterate data elements.

Here is a react component to iterate data

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

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

export default LocalFileRead;

How to read the external file using fetch in Class Components

This is another way of reading an external json file, It can be local or external API Url.

You can use Axios or fetch to read from local JSOn or External API calls.

In react component,

  • Create state property to hold employee json file
  • Inside the componentDidMount() callback method, use fetch to access the json local file and read json content and update state property with json content.
  • Inside render, read state data, and print to the component.
import React, { Component } from "react";
import employee from "./employee.json";
class LocalFileRead extends Component {
  constructor(props) {
    super(props);
    this.state = {
      employee: [],
    };
  }

  componentDidMount() {
    fetch("./employee.json")
      .then((res) => res.json())
      .then((data) => {
        console.log(data);

        this.setState({ employee: JSON.stringify(data) }, () => {
          alert(this.state.hugeText);
        });
      });
  }
  render() {
    const emp = this.state.employee;
    return (
      <div>
        <ul>
          {emp.map((record, i) => (
            <li key={i}>
              {record.id} - {record.firstName} {record.firstName}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

export default LocalFileRead;

How to read local json file in react functional component with fetch and useEffect

The following are the steps required for the functional component employee.json is placed in the public folder

  • First, create a state object using the useState hook, with the initial value as empty array employees, setEmployee method added to change state
  • useEffect is added with functional expression and empty array parameters.
  • In functional expression, get data using fetch from the local json file located in the public folder.
  • Display the data in return expression

Here is a code

import React, { useEffect, useState } from "react";

function ReadFile() {
  const [employees, setEmployee] = useState([]);

  useEffect(() => {
    getAPI("./employee.json");
  }, []);

  const getAPI = (data) => {
    console.log(data);
    fetch(data, {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        setEmployee(data);
      });
  };

  return (
    <div>
      <ul>
        {employees.map((record, i) => (
          <li key={i}>
            {record.id} - {record.firstName} {record.firstName}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ReadFile;

Conclusion

Learn multiple ways to read json files in React with examples.