A2oz

How Do I Import a JSON Server Into React?

Published in React Development 2 mins read

You can easily integrate a JSON server into your React application using the json-server package.

Setting Up JSON Server

  1. Install JSON Server:

    npm install -g json-server
  2. Create a JSON file:
    Create a file named db.json in your project's root directory and populate it with the data you want to use. For example:

    {
      "posts": [
        { "id": 1, "title": "Post 1", "content": "This is the content of post 1." },
        { "id": 2, "title": "Post 2", "content": "This is the content of post 2." }
      ]
    }
  3. Start JSON Server:
    Run the following command in your terminal:

    json-server --watch db.json

    This will start a local server at http://localhost:3000/ with your data.

Importing Data into React

  1. Install Axios:

    npm install axios
  2. Fetch Data in your React Component:
    Use Axios to fetch data from the JSON server.

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    function MyComponent() {
      const [posts, setPosts] = useState([]);
    
      useEffect(() => {
        const fetchPosts = async () => {
          const response = await axios.get('http://localhost:3000/posts');
          setPosts(response.data);
        };
    
        fetchPosts();
      }, []);
    
      return (
        <div>
          <h1>Posts</h1>
          <ul>
            {posts.map((post) => (
              <li key={post.id}>
                <h2>{post.title}</h2>
                <p>{post.content}</p>
              </li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default MyComponent;

Explanation

  • The json-server package creates a local server that serves your data from a JSON file.
  • You can access the data from the server using an HTTP client like Axios.
  • The useEffect hook fetches data from the server when the component mounts.
  • The map method iterates through the data and renders each post.

Conclusion

By following these simple steps, you can easily import a JSON server into your React application and use its data in your components.

Related Articles