Fake Store -API-Fetching -Mapping-in-React js
To map data from the Fake Store API in a React application, follow these steps to fetch data and display it using .map()
.
Step-by-Step Guide
1. Set Up a React Project
If you don’t have a React project set up, create one with:
npx create-react-app fake-store-app
Navigate to the project directory: cd fake-store-app
2. Fetch Data from Fake Store API
The Fake Store API endpoint (https://fakestoreapi.com/products
) provides mock product data in JSON format. You can fetch the data in a component, such as App.js
or a separate component.
3. Create the Component to Fetch and Display Data
In App.js
, add the following:
import React, { useEffect, useState } from 'react';
Explanation of Code
State and useEffect:
- We define
products
using the useState
hook to
store the fetched data. - Inside
useEffect
, the API call is made,
and the response is saved in products
.
Mapping the Data:
- We use
.map()
on the products
array to
render each product. - Each product item includes an
image, title, and price.
State and useEffect:
- We define
products
using theuseState
hook to store the fetched data. - Inside
useEffect
, the API call is made, and the response is saved inproducts
.
- We define
Mapping the Data:
- We use
.map()
on theproducts
array to render each product. - Each product item includes an image, title, and price.
- We use
4. Run the Project
To view your app in the browser, run:
To view your app in the browser, run:
Styling (Optional)
You can add some CSS to style the product list:
.product-list { display: flex; flex-wrap: wrap; gap: 20px;}
.product { border: 1px solid #ddd; padding: 10px; width: 200px; text-align: center;}
You can add some CSS to style the product list: