DEV Community

Cover image for How to Use JSON Placeholder in a React JS Project.
zenixtech
zenixtech

Posted on

How to Use JSON Placeholder in a React JS Project.

When developing a React application, you often need APIs for testing. JSON Placeholder is a great free resource that provides mock data for prototyping and development. In this post, I'll demonstrate how to use JSONPlaceholder in your React project. Additionally, we'll learn how to fetch and use a custom JSON file hosted online.

What is JSON Placeholder?
JSON Placeholder is a free online REST API that provides various endpoints to work with mock data like posts, comments, users, and more. It’s an excellent tool for learning and testing API calls without needing to set up your own server.
Website: JSON Placeholder.

Setting Up the React Project:
To follow along, ensure you have Node.js installed and a React app set up. If you don’t already have one, create it using:

npx create-react-app json-placeholder-demo
cd json-placeholder-demo

Enter fullscreen mode Exit fullscreen mode

Install axios for making API requests (optional):

npm install axios

Enter fullscreen mode Exit fullscreen mode

Fetching Data from JSON Placeholder
Let's create a React component to fetch and display posts from JSON Placeholder.

JsonPlaceholder.jsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./main.css"; // Import the CSS file

const JsonPlaceholder = () => {
  const [users, setUsers] = useState([]);

  // Fetch data from JSON Placeholder
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get(
          "https://jsonplaceholder.typicode.com/users"
        );
        setUsers(response.data); // Fetch all users
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchUsers();
  }, []);

  return (
    <div className="user-container">
      <h1 className="header">User Profiles</h1>
      <div className="card-container">
        {users.map((user) => (
          <div key={user.id} className="user-card">
            <h2 className="user-name">{user.name}</h2>
            <p className="user-detail">
              <strong>Username:</strong> {user.username}
            </p>
            <p className="user-detail">
              <strong>Email:</strong> {user.email}
            </p>
            <p className="user-detail">
              <strong>Phone:</strong> {user.phone}
            </p>
            <p className="user-detail">
              <strong>Address:</strong> {user.address.street},{" "}
              {user.address.city}
            </p>
            <p className="user-detail">
              <strong>Company:</strong> {user.company.name}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default JsonPlaceholder;

Enter fullscreen mode Exit fullscreen mode

main.css

/* General Styles */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f8f9fa;
}

/* Header Styles */
.header {
  text-align: center;
  margin: 20px 0;
  color: #343a40;
  font-size: 2rem;
  font-weight: bold;
}

/* Container for Cards */
.user-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  width: 100%;
  max-width: 1200px;
}

/* Card Styles */
.user-card {
  background-color: #ffffff;
  border: 1px solid #dee2e6;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

/* User Information */
.user-name {
  font-size: 1.5rem;
  color: #007bff;
  margin-bottom: 10px;
}

.user-detail {
  font-size: 1rem;
  color: #495057;
  margin: 5px 0;
}

.user-detail strong {
  color: #343a40;
}

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Using Custom JSON Data
Let’s now use a custom JSON file hosted at:
Sudhanshu_Developer

This JSON file contains a list of food items. Here's how to fetch and display it.

FoodApi.jsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./FoodMain.css"; 

const FoodApi = () => {
  const [foods, setFoods] = useState([]);
  const [filteredFoods, setFilteredFoods] = useState([]);
  const [filter, setFilter] = useState({ category: "All", country: "All" });

  // Fetch data from local JSON file or URL
  useEffect(() => {
    const fetchFoods = async () => {
      try {
        const response = await axios.get(
          "https://sudhanshu1919.github.io/FoodJson/Foodapi.json"
        );
        setFoods(response.data);
        setFilteredFoods(response.data);
      } catch (error) {
        console.error("Error fetching food data:", error);
      }
    };

    fetchFoods();
  }, []);

  return (
    <div className="food-container">
      <h1 className="food-header">Food Items</h1>

      <div className="food-card-container">
        {filteredFoods.map((food) => (
          <div key={food.id} className="food-card">
            <div className="inner-card">
              <div>
                <img
                  src={food.image}
                  alt={food.foodname}
                  className="food-image"
                />
              </div>
              <div>
                <h3 className="food-name">{food.foodname}</h3>
                <p className="food-detail">
                  <strong>Category:</strong> {food.category}
                </p>
                <p className="food-detail">
                  <strong>Price:</strong> {food.prise}
                </p>
                <p className="food-detail">
                  <strong>Country:</strong> {food.country}
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default FoodApi;

Enter fullscreen mode Exit fullscreen mode

FoodMain.css

/* General Styles */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f3f4f6;
}

/* Header */
.food-header {
  text-align: center;
  margin: 20px 0;
  font-size: 2.5rem;
  color: #34495e;
  font-weight: bold;
}

/* Food Cards Container */
.food-card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* Food Card */
.food-card {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.food-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

/* Food Details */
.food-name {
  font-size: 1.5rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.food-detail {
  font-size: 1rem;
  color: #131414;
  margin: 5px 0;
}

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Conclusion
Using JSON Placeholder is an excellent way to learn about API integration in React. Similarly, hosting and using your custom JSON files helps you prototype with real-world data. Practice integrating various APIs and understand how to handle API responses effectively.

Happy coding! 🚀

Top comments (0)