Create an HTML table clicking on a cell of which activates that cell by providing some additional css to it.
Note: Only one cell can be active at a time.
AppTable.js
import React, { useEffect, useState } from "react";
// import { useEffect, useState } from "react";
import axios from "axios";
import './ApiTable.css'
const ApiTable = () => {
const [userList, setUserList] = useState([]);
const [selectedCell, setSelectedCell] = useState({row:-1, col:-1});
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((res) => {
console.log(res);
setUserList(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
const clickCell = (index, column) => {
setSelectedCell({row: index, col: column});
}
return (
<div className="table-container">
<table className="table-style">
<tr>
<th>ID</th>
<th>name</th>
<th>Username</th>
{/* <th>Email</th>
<th>Phone</th>
<th>Website</th> */}
</tr>
{userList.map((user, index) => {
return (
<tr onClick= {(e)=>{console.log(e)}}key={user.id}>
<td className = {(index==selectedCell.row && selectedCell.col==0)?"selected-cell":null} onClick={() => {clickCell(index, 0)}}>{user.id}</td>
<td className = {(index==selectedCell.row && selectedCell.col==1)?"selected-cell":null} onClick={()=>{clickCell(index, 1)}}>{user.name}</td>
<td className = {(index==selectedCell.row && selectedCell.col==2)?"selected-cell":null} onClick={()=>{clickCell(index, 2)}}>{user.username}</td>
{/* <td>{user.email}</td>
<td>{user.phone}</td>
<td>{user.website}</td> */}
</tr>
);
})}
</table>
</div>
);
};
export default ApiTable;
AppTable.css
/* .table-style{
border: 1px solid black;
} */
.table-container{
display: flex;
justify-content: center;
align-items: center;
}
table, td, th{
border: 2px solid red;
border-collapse: collapse;
align-items: center;
}
.selected-cell{
color: yellow;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import ApiTable from './ApiTable';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ApiTable />
</React.StrictMode>
);
reportWebVitals();
Top comments (0)