<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel">
const { useState } = React;
const initialProducts = [
{ id: 1, name: "Laptop", price: 25.99 },
{ id: 2, name: "Mobile", price: 15.99 },
{ id: 3, name: "Desktop", price: 35.99 },
{ id: 4, name: "Tablet", price: 19.99 },
{ id: 5, name: "Smartwatch", price: 10.49 },
{ id: 6, name: "Headphones", price: 8.99 },
{ id: 7, name: "Keyboard", price: 12.99 },
{ id: 8, name: "Mouse", price: 7.49 },
{ id: 9, name: "Monitor", price: 29.99 },
{ id: 10, name: "Printer", price: 45.99 },
{ id: 11, name: "External Hard Drive", price: 49.99 },
{ id: 12, name: "Speakers", price: 21.99 },
{ id: 13, name: "Webcam", price: 14.99 },
{ id: 14, name: "Gaming Console", price: 199.99 },
{ id: 15, name: "Router", price: 9.99 },
const [products, setProducts] = useState(initialProducts);
const [sortOrder, setSortOrder] = useState("asc");
const toggleSortOrder = () => {
const newSortOrder = sortOrder === "asc" ? "desc" : "asc";
setSortOrder(newSortOrder);
// Sort the products based on the price and sorting order
const sortedProducts = [...products].sort((a, b) => {
if (newSortOrder === "asc") {
return a.price - b.price;
return b.price - a.price;
setProducts(sortedProducts);
<div className='container'>
<h1>React js Table Sort By Price</h1>
<table className='table'>
<th className='table-header'>ID</th>
<th className='table-header'>Name</th>
<th className='table-header' onClick={toggleSortOrder}>
{sortOrder === "asc" ? <span>↑</span> : <span>↓</span>}
{products.map((product) => (
<tr key={product.id} className='table-row'>
<td className='table-data'>{product.id}</td>
<td className='table-data'>{product.name}</td>
<td className='table-data'>${product.price.toFixed(2)}</td>
ReactDOM.render(<App />, document.getElementById("app"));
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-collapse: collapse;
/* Styles for table header */
/* Styles for table header when sorting is active */
/* Styles for table rows */
border-bottom: 1px solid #ddd;
/* Styles for table data cells */
/* Styles for alternating table rows */
.table tr:nth-child(even) {
background-color: #f2f2f2;
/* Styles for the sorting arrow */
/* Hover effect for table rows */
background-color: #e0e0e0;