Displaying API Data in Components in React JS
Displaying API data in React components is an important skill for building dynamic and interactive web applications. APIs allow React applications to retrieve information from external servers, such as user profiles, product details, weather reports, news articles, and order information. React components can display this information using JSX, props, state, and JavaScript array methods.
React JS Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Does Displaying API Data Mean?
Displaying API data means fetching information from an API, storing the response in a suitable variable or React state, and rendering that information inside a component using JSX.
For example, an API may return a list of products containing product IDs, names, prices, and images. React can display these details as product cards.
Example API Response
{
"id": 1,
"name": "Laptop",
"price": 55000,
"category": "Electronics"
}
React can use these properties to display a product name, price, and category on the webpage.
2. How API Data Is Displayed in React
- Send a request to the API using Fetch API or a library such as Axios.
- Receive the server response.
- Convert the response into JavaScript data, usually with
response.json() when using Fetch.
- Store the data in React state when the component needs to update as data changes.
- Use JSX to display the data.
- Handle loading, empty, and error states to improve the user experience.
Basic Workflow
React Component
↓
Send API Request
↓
Receive API Response
↓
Convert Response to JSON
↓
Store Data in State
↓
Render Data Using JSX
↓
Display Information on Screen
3. Using JSX to Display API Data
JSX allows developers to combine JavaScript expressions with HTML-like syntax. To display a value stored in a JavaScript variable, use curly braces {} inside JSX.
Example
function Product() {
const product = {
name: "Laptop",
price: 55000
};
return (
<div>
<h2>{product.name}</h2>
<p>Price: ₹{product.price}</p>
</div>
);
}
export default Product;
Output: The component displays the product name as Laptop and its price as ₹55000.
Important: Use curly braces to display JavaScript values in JSX. Ordinary text can be written directly between JSX tags.
4. Fetching API Data with the Fetch API
The Fetch API is a built-in browser feature that sends HTTP requests and returns a Promise. In React, it is commonly used with useEffect() to fetch data after a component renders and with useState() to store the result.
Example: Fetch and Display a User
import { useEffect, useState } from "react";
function UserProfile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function fetchUser() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
if (!response.ok) {
throw new Error("Failed to fetch user data");
}
const data = await response.json();
setUser(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUser();
}, []);
if (loading) {
return <p>Loading user details...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
if (!user) {
return <p>No user data available.</p>;
}
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>City: {user.address.city}</p>
</div>
);
}
export default UserProfile;
Explanation
useState() stores the user information, loading status, and error message.
useEffect() starts the API request after the component renders.
fetch() sends a request to the API endpoint.
response.ok checks whether the HTTP response status indicates success.
response.json() parses the JSON response body.
setUser(data) stores the returned information in state.
- React re-renders the component when its state changes.
- The conditional statements display loading, error, empty, or user information as appropriate.
Note: Fetch does not automatically reject its Promise for HTTP errors such as 404 or 500. Check response.ok before processing the response.
5. Displaying Multiple API Records Using map()
APIs frequently return arrays containing multiple records. React's map() method can transform each array item into JSX elements.
Example API Data
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mobile", price: 25000 },
{ id: 3, name: "Headphones", price: 2000 }
];
Example Component
function ProductList() {
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mobile", price: 25000 },
{ id: 3, name: "Headphones", price: 2000 }
];
return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
</div>
);
}
export default ProductList;
Expected Output
- Laptop - ₹55000
- Mobile - ₹25000
- Headphones - ₹2000
Why Is the key Prop Important?
The key prop helps React identify individual elements in a rendered list. Use a stable and unique ID from the API whenever possible.
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>₹{product.price}</p>
</div>
))}
Avoid generating random keys during rendering. Array indexes are also not ideal when list items can be inserted, deleted, or reordered.
6. Storing API Data in React State
React state is useful when API data changes over time and the component must update automatically when new data is received.
Example
import { useState } from "react";
function UserExample() {
const [user, setUser] = useState({
name: "Aarav",
email: "[email protected]"
});
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
<button
onClick={() => setUser({
name: "Priya",
email: "[email protected]"
})}
>
Change User
</button>
</div>
);
}
export default UserExample;
When the button is clicked, the state updates and React renders the new user details. This example uses local data to demonstrate state updates; an actual API integration would set state using the returned API response.
State vs. Ordinary Variables
| Feature |
React State |
Ordinary Variable |
| Stores data |
Yes |
Yes |
| Triggers re-render when updated |
Yes, when updated through the setter |
No |
| Suitable for changing API data shown in the UI |
Yes |
Usually not by itself |
| Example |
setUser(data) |
let name = "Aarav" |
7. Passing API Data to Child Components with Props
React props allow a parent component to pass API data to child components. This approach helps divide a large interface into smaller, reusable components.
Parent Component
function ProductPage() {
const product = {
id: 1,
name: "Wireless Headphones",
price: 2500
};
return <ProductCard product={product} />;
}
Child Component
function ProductCard({ product }) {
return (
<div className="product-card">
<h3>{product.name}</h3>
<p>Price: ₹{product.price}</p>
</div>
);
}
export default ProductCard;
How it works: The parent provides the product object through the product prop. The child component reads its properties and displays them. In a real application, the parent can pass the object received from an API.
8. Displaying Nested API Data
Some APIs return nested objects. To display nested values, access each property through its parent object.
Example Data
{
"id": 1,
"name": "Aarav",
"address": {
"city": "Mumbai",
"zipcode": "400001"
}
}
Displaying Nested Properties
<h2>{user.name}</h2>
<p>City: {user.address.city}</p>
<p>ZIP Code: {user.address.zipcode}</p>
If a nested object might be missing, use optional chaining to avoid errors when accessing its properties.
<p>City: {user.address?.city ?? "Not available"}</p>
Optional chaining prevents an error when address is null or undefined. The nullish coalescing operator supplies a fallback value when the result is null or undefined.
9. Displaying Loading, Error, and Empty States
API requests take time and may fail. A good React component should communicate the current state to users instead of displaying a blank area.
| State |
Purpose |
Example Message |
| Loading |
Shows that a request is in progress |
Loading products... |
| Success |
Displays the returned data |
Product list |
| Empty |
Indicates that no records were returned |
No products found. |
| Error |
Explains that the request failed |
Unable to load products. |
Conditional Rendering Example
{loading && <p>Loading...</p>}
{error && <p>{error}</p>}
{!loading && !error && products.length === 0 && (
<p>No products found.</p>
)}
{!loading && !error && products.length > 0 && (
<ProductList products={products} />
)}
In this example, the conditions are designed to avoid showing the loading, error, empty, and success states simultaneously. Make sure the initial values of your state variables match the expected data types.
10. Complete Example: Fetching and Displaying API Products
The following component fetches product records from a sample API endpoint, stores them in state, and displays the returned records as a list. It also handles loading, errors, and empty results.
import { useEffect, useState } from "react";
function ApiProducts() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://dummyjson.com/products",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Unable to fetch products");
}
const data = await response.json();
setProducts(
Array.isArray(data.products) ? data.products : []
);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchProducts();
return () => controller.abort();
}, []);
if (loading) {
return <p>Loading products...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
if (products.length === 0) {
return <p>No products available.</p>;
}
return (
<div>
<h2>Products</h2>
<div className="product-list">
{products.map((product) => (
<div className="product-card" key={product.id}>
<img
src={product.thumbnail}
alt={product.title}
width="120"
/>
<h3>{product.title}</h3>
<p>Price: ${product.price}</p>
<p>Rating: {product.rating}</p>
</div>
))}
</div>
</div>
);
}
export default ApiProducts;
Explanation of the Complete Example
products stores the array of product objects.
loading indicates whether the request is in progress.
error stores an error message if the request fails.
AbortController cancels the request when the component is cleaned up.
Array.isArray() checks that the API field contains an array before saving it.
map() creates one product card for each product record.
key={product.id} gives each card a stable key.
- The image, title, price, and rating are rendered from the API response.
Note: This example assumes the API returns a products array with the specified fields. The component should be adjusted if the actual API uses a different response structure.
11. Styling API Data with CSS
CSS can make API data easier to read by arranging records into cards, grids, or tables.
Example CSS
.product-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
.product-card {
padding: 16px;
border: 1px solid #ddd;
border-radius: 8px;
background: #fff;
}
.product-card img {
max-width: 100%;
height: auto;
object-fit: contain;
}
.product-card h3 {
margin-bottom: 8px;
}
These styles create a responsive grid of product cards. You can modify the CSS to match the design of your application.
12. Common Mistakes When Displaying API Data
| Mistake |
Why It Happens |
Solution |
| Reading data before it arrives |
API requests are asynchronous |
Use suitable initial state and loading checks |
Forgetting response.json() |
Fetch returns a Response object |
Parse the JSON response body when appropriate |
| Ignoring HTTP errors |
Fetch may resolve even for 404 or 500 responses |
Check response.ok |
Calling map() on an object |
The API response may not be an array |
Check the response structure and validate the array |
| Missing list keys |
List elements lack stable identities |
Use a unique ID in the key prop |
| Accessing missing nested properties |
Some fields may be absent |
Use optional chaining and fallback values |
| Showing no loading indicator |
The request takes time |
Track loading state |
| Ignoring request cleanup |
The component may unmount before a request finishes |
Use cancellation where appropriate |
13. Best Practices for Displaying API Data
- Keep API request logic organized and separate from complex presentation logic when appropriate.
- Use React state to store data that affects the rendered UI.
- Use
useEffect() for client-side fetching when synchronization with an external API is needed.
- Always handle loading, error, and empty states.
- Validate the response structure before accessing properties or calling array methods.
- Use stable, unique keys when rendering lists.
- Use reusable components for cards, tables, profile details, and other repeated UI elements.
- Avoid storing sensitive API keys in client-side source code.
- Cancel obsolete requests when appropriate, especially when parameters change or components unmount.
- For larger applications, consider a dedicated data-fetching library or the framework's recommended data-loading approach.
14. Real-World Applications
- E-commerce websites: Display product names, images, prices, and stock availability.
- Weather applications: Display temperature, humidity, and weather conditions.
- News applications: Display article titles, descriptions, images, and publication dates.
- Admin dashboards: Display users, orders, revenue, and reports.
- Social applications: Display profiles, posts, comments, and follower information.
- Booking applications: Display available services, schedules, and booking details.
15. Practice Project: API Product Dashboard
Create a React application that retrieves product information from an API and displays it in a responsive dashboard.
Project Requirements
- Fetch product data from an API endpoint.
- Display product images, titles, prices, and ratings.
- Show a loading message while the request is in progress.
- Display a useful error message if the request fails.
- Show an empty-state message when there are no products.
- Use
map() to render multiple product cards.
- Use a stable product ID as the React key.
- Style the product cards using CSS Grid or Flexbox.
- Add a search input to filter products by title.
- Move the product card into a reusable child component.
Expected Learning Outcome
After completing this project, you should understand how to retrieve API data, store it in React state, pass data through props, render dynamic lists, and manage common API request states.
16. Interview Questions and Answers
Q1. How do you display API data in React?
Answer: Fetch the data from an API, parse the response, store it in state, and display it in JSX. Use loading and error handling where appropriate.
Q2. Why is useState used when displaying API data?
Answer: It stores data that affects the UI. Updating state with its setter causes React to render the updated information.
Q3. Why is useEffect commonly used for API calls?
Answer: In client-side components, it can synchronize with an external system such as an API after rendering. The effect's dependencies determine when it runs again.
Q4. How do you display an array returned by an API?
Answer: Use the JavaScript map() method to transform each array item into JSX.
Q5. What is the purpose of the key prop?
Answer: It helps React identify list elements between renders, especially when items are inserted, removed, or reordered.
Q6. How do you handle API errors?
Answer: Check HTTP response status, catch request or parsing errors, store an error message, and display an appropriate message to the user.
Q7. What happens if API data has not loaded yet?
Answer: The component may initially render using its initial state. Use loading indicators and conditional rendering, and avoid accessing properties that do not yet exist.
Q8. How can API data be passed to a child component?
Answer: Pass the data as a prop from the parent and read it in the child component.
Q9. What is conditional rendering?
Answer: Conditional rendering means displaying different JSX based on conditions, such as loading status, errors, or whether data exists.
Q10. Why should API response data be validated?
Answer: APIs may return unexpected or missing fields. Validation prevents incorrect assumptions about the response structure and reduces runtime errors.
17. Quick Revision Checklist
- Understand what an API response contains.
- Know how to request and parse JSON data.
- Understand the role of
useState() and useEffect().
- Display object properties using JSX curly braces.
- Render arrays with
map() and stable keys.
- Pass API data to child components through props.
- Access nested properties safely.
- Handle loading, success, empty, and error states.
- Validate response structures and handle failed HTTP responses.
- Build a small API-powered React project.
18. Conclusion
Displaying API data in React components is a fundamental skill for developing modern web applications. By combining Fetch API, React state, effects, JSX, props, and array methods such as map(), developers can create dynamic interfaces that display live information from external services. Proper loading indicators, error handling, response validation, and reusable components help make these applications more reliable and easier to maintain.
Learn more through JustAcademy React JS Training and register for a React JS Course Demo.
19. Official Learning Resources