Next.js Reading and Display Data from a Local JSON File

nextjs

To read and display data from a local JSON file in a Next.js app, you can use the following steps:

  1. Create a data directory in the root of your Next.js app and place the JSON file in this directory.

  2. In the component where you want to display the data, import the JSON file using the import statement.

  3. Use the useEffect hook to fetch the data from the JSON file and store it in a state variable.

Here is an example of how you can read and display data from a local JSON file in a Next.js app:

import {useState, useEffect} from 'react';
import data from '../data/data.json';

function Home() {
    const [items, setItems] = useState([]);

    useEffect(() => {
        setItems(data.items);
    }, []);

    return (
        <ul>
            {items.map(item => (
                <li key={item.id}>{item.name}</li>
            ))}
        </ul>
    );
}

export default Home;

In this example, the data variable is imported from the data.json file in the data directory. The useEffect hook is used to fetch the items array from the data object and store it in the items state variable. The component then displays the names of the items in an unordered list.

For more information on how to use the useEffect hook in a Next.js app, you can refer to the React documentation: https://reactjs.org/docs/hooks-effect.html.