<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 [data, setData] = useState([
{ date: "2023-05-25", name: "Sophia Anderson", age: 33 },
{ date: "2023-05-07", name: "Alexander Lee", age: 29 },
{ date: "2023-05-09", name: "Ella Harris", age: 31 },
{ date: "2023-05-14", name: "Andrew Miller", age: 42 },
{ date: "2023-05-11", name: "Grace Wilson", age: 23 },
{ date: "2023-05-22", name: "Benjamin Lewis", age: 39 },
{ date: "2023-05-28", name: "Ava Hall", age: 26 },
{ date: "2023-05-19", name: "Joseph Young", age: 36 },
{ date: "2023-05-29", name: "Mia Turner", age: 34 },
{ date: "2023-05-17", name: "David Scott", age: 41 },
{ date: "2023-05-23", name: "Abigail Green", age: 27 },
{ date: "2023-05-02", name: "James Allen", age: 37 },
{ date: "2023-05-06", name: "Elizabeth Baker", age: 30 },
{ date: "2023-05-21", name: "Christopher Adams", age: 33 },
{ date: "2023-05-13", name: "Isabella Turner", age: 24 },
{ date: "2023-05-24", name: "Henry Hill", age: 43 },
{ date: "2023-05-04", name: "Lily Allen", age: 29 },
const [sortDirection, setSortDirection] = useState("asc");
const [sortBy, setSortBy] = useState("date");
// Function to handle sorting by date or age
const handleSort = (sortBy) => {
const sortedData = [...data];
sortedData.sort((a, b) => {
const dateA = new Date(a.date);
const dateB = new Date(b.date);
return sortDirection === "asc" ? dateA - dateB : dateB - dateA;
} else if (sortBy === "age") {
return sortDirection === "asc" ? a.age - b.age : b.age - a.age;
setSortDirection(sortDirection === "asc" ? "desc" : "asc");
<div className="container">
<h2>React Js Table Sort by Age</h2>
<button onClick={() => handleSort("date")}>
(sortDirection === "asc" ? (
<button onClick={() => handleSort("age")}>
(sortDirection === "asc" ? (
{data.map((item, index) => (
ReactDOM.render(<App />, document.getElementById("app"));
/* Styling for the container */
font-family: Arial, sans-serif;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12),
0 2px 4px 0 rgba(0, 0, 0, 0.24);
/* Styling for the header */
/* Styling for the sort buttons */
background-color: #4caf50;
/* Styling for the table */
border-collapse: collapse;
border-bottom: 1px solid #ddd;
background-color: #f2f2f2;
/* Styling for table rows */
background-color: #f5f5f5;
/* Styling for alternating row colors */
background-color: #f2f2f2;