Creating a Sortable Data Table with React and an API

I am a MERN stack developer. Here to learn and share my knowledge to help other to grow.
In this tutorial, we'll learn how to create a data table in React that displays data from an API and includes a dropdown menu for sorting the data by a specific field.
We'll fetch data from the API and display the data in a table, with each object in the array having a title field.
When the user selects either "A-Z" or "Z-A" in the sort by dropdown menu, the data will be sorted in ascending or descending order by the title field. Follow along as we build this useful feature in a React application.
Here is some example code for a React component that fetches data from a JSON API and displays the data in a list.
The component also includes a dropdown menu that allows the user to sort the data by title in ascending or descending order:
import React, { useState, useEffect } from 'react';
function ProductList() {
const [products, setProducts] = useState([]);
const [sortDirection, setSortDirection] = useState('asc');
useEffect(() => {
async function fetchData() {
const response = await fetch('https://fakestoreapi.com/products?limit=5');
const data = await response.json();
setProducts(data);
}
fetchData();
}, []);
function sortByTitle(direction) {
setSortDirection(direction);
const sortedProducts = [...products].sort((a, b) => {
if (direction === 'asc') {
return a.title.localeCompare(b.title);
} else {
return b.title.localeCompare(a.title);
}
});
setProducts(sortedProducts);
}
return (
<div>
<h1>Product List</h1>
<label htmlFor="sort-direction">Sort by title:</label>
<select id="sort-direction" onChange={e => sortByTitle(e.target.value)}>
<option value="asc">A-Z</option>
<option value="desc">Z-A</option>
</select>
<ul>
{products.map(product => (
<li key={product.id}>{product.title}</li>
))}
</ul>
</div>
);
}
export default ProductList;
This component uses React's useState and useEffect hooks to handle state and side effects (such as fetching data from an API).
The component fetches data from the API when it mounts and stores the data in the products state variable.
The dropdown menu allows the user to select either "A-Z" or "Z-A", and the sortByTitle function is called with the corresponding sort direction when the selection changes.
The function sorts the products array and updates the state with the sorted array, causing the component to re-render and display the sorted data.
