<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React;
const data = [
{ id: 1, name: "John", age: 25 },
{ id: 2, name: "Jane", age: 30 },
{ id: 3, name: "Bob", age: 35 },
{ id: 4, name: "Sarah", age: 28 },
{ id: 5, name: "Michael", age: 32 },
{ id: 6, name: "Emily", age: 27 },
{ id: 7, name: "David", age: 40 },
{ id: 8, name: "Amy", age: 29 },
{ id: 9, name: "Daniel", age: 33 },
{ id: 10, name: "Olivia", age: 26 },
{ id: 11, name: "Matthew", age: 31 },
{ id: 12, name: "Sophia", age: 38 },
{ id: 13, name: "James", age: 24 },
{ id: 14, name: "Emma", age: 36 },
{ id: 15, name: "Christopher", age: 34 },
{ id: 16, name: "Ava", age: 29 },
{ id: 17, name: "Andrew", age: 27 },
{ id: 18, name: "Mia", age: 33 },
];
function App() {
const handleClick = (rowIndex, cellIndex) => {
const cellData =
data[rowIndex][Object.keys(data[rowIndex])[cellIndex]];
console.log(
`Cell clicked: Row ${rowIndex}, Cell ${cellIndex}, Value: ${cellData}`
);
};
return (
<div className="container">
<h3>React Js Table Cell Clickable</h3>
<table className="custom-table">
<thead>
<tr>
<th>S.no</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{data.map((row, rowIndex) => (
<tr key={row.id}>
{Object.values(row).map((cell, cellIndex) => (
<td
key={cellIndex}
onClick={() => handleClick(rowIndex, cellIndex)}
className="cell"
>
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
.container {
margin: 0 auto;
width: 500px;
text-align: center;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12),
0 2px 4px 0 rgba(0, 0, 0, 0.24);
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.custom-table {
border-collapse: collapse;
width: 100%;
max-width: 600px;
background-color: #f7f7f7;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
font-family: Arial, sans-serif;
}
.custom-table thead th {
background-color: #333;
color: #fff;
padding: 12px;
}
.custom-table tbody tr:nth-child(even) {
background-color: #f2f2f2;
}
.custom-table tbody td {
padding: 12px;
}
.cell {
cursor: pointer;
}
.cell:hover {
background-color: #e2e2e2;
}
</style>
</body>
</html>