'How to get the value of clicked cell in React Material Table?
I am trying to get the corresponding value of cell in React Material UI Table Component.
I was looking for already predefined component api properties but couldn't find anything appropriate.
Working with Material UI DataGrid component, I achieved that, getting the selected row via onSelectionModelChange
thanks to this answer.
But in this case, Table doesn't have any checkboxes and I need to retrieve the data by clicking.
Here is the codesandbox link and the example code:
import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
export default function BasicTable({ users }: any) {
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>userId</TableCell>
<TableCell align="right">id</TableCell>
<TableCell align="right">Title</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users &&
users.map((user: any) => (
<TableRow
key={users.id}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
>
<TableCell align="right">{user.userId}</TableCell>
<TableCell align="right">{user.id}</TableCell>
<TableCell align="right">{user.title}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
Any help will be appreciated.
Solution 1:[1]
You can create an onClick
function on the cells that you want this behavior to happen. Assuming that you want this on user.title
cells and using console.log
as example:
<TableCell align="right" onClick={({target}) => console.log(target.textContent)}>{user.title}</TableCell>
Solution 2:[2]
Since you are mapping over your data, you can simply use the desired data from the map:
{users &&
users.map((user: any) => (
<TableRow
key={user.id}
onClick={() => console.log(user.id)} // set desired state here
>
<TableCell align="right">{user.userId}</TableCell>
<TableCell align="right">{user.id}</TableCell>
<TableCell align="right">{user.title}</TableCell>
</TableRow>
))}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel Baldi |
Solution 2 | Bryana K. |