Skip to main content

how to use .json file in react

 Reading a .json file in a React application is quite straightforward. Here are the steps to do it:

  1. Create a JSON file: First, create a JSON file with some data. For example, let’s name it data.json and place it in the src folder of your React project.

    {
      "users": [
        { "id": 1, "name": "John Doe" },
        { "id": 2, "name": "Jane Smith" }
      ]
    }
    
  2. Import the JSON file: In your React component, import the JSON file.

    import React from 'react';
    import data from './data.json';
    
    const App = () => {
      return (
        <div>
          <h1>User List</h1>
          <ul>
            {data.users.map(user => (
              <li key={user.id}>{user.name}</li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default App;
    
  3. Run your React app: Start your React application using npm start or yarn start, and you should see the list of users displayed on the screen.

This method works well for small JSON files and local data. If you need to fetch data from an external API, you can use libraries like Axios or the Fetch API12.

Would you like more details on fetching data from an external source or anything else?






Comments