Tom
Tom

Reputation: 83

Retrieving value from row on click on button in grid React MUI

A project I am involved with has a react user grid component. The grid is populated by requesting data from the server. When I click on a button in a grid row, I need to get the value of the "_id" field of this particular row. I only managed to get the _id of all rows, but I only need the value of the row where the button was clicked. In addition, the button click event occurs immediately on page load, not just on click. enter image description here

    const columns = [
  {
    field: '_id', headerName: 'id', type: 'number', flex: 0.9,
  },
  {
    field: 'userName', headerName: 'Username', flex: 0.7,
  },
  {
    field: 'email', headerName: 'email', flex: 0.7,
  },
  {
    field: 'fullName', headerName: 'Full name', flex: 0.7,
  },
  {
    field: 'status', headerName: 'Status', flex: 0.7,
  },
  {
    field: 'actions',
    type: 'actions',
    headerName: 'Actions',
    flex: 0.2,
    getActions: (params) => [
      <IconButton onClick={console.log(params.row._id)}>
        <EditIcon />
      </IconButton>,
    ],
  },
];

function generateRows(users) {
  return users.map((user) => (({
    _id, userName, email, fullName, status,
  }) => ({
    _id, userName, email, fullName, status,
  }))(user));
}

export default function UserControlTable() {
  const [data, setData] = useState({
    users: [],
  });

  useEffect(() => {
    const fetchUsers = async () => {
      const users = await axios.get(process.env.REACT_APP_API_URL + USER_LIST);
      setData({ users: generateRows(users.data)});
    };
    fetchUsers();
  }, []);
  return (
    <Container>
      <DataGrid
        getRowId={(row) => row._id}
        rows={data.users}
        columns={columns}
        checkboxSelection
        column
      />
    </Container>
  );
}

Upvotes: 1

Views: 5021

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 9981

This is how you can achieve the click event on Grid:

import Grid from '@mui/material/Grid';

const handleGridClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
  console.log('Grid click');
  console.log(event);
}


export default function ClickableGrid() {
  return (
    <Grid onClick={handleBoxClick}>
         // Rest of the codes
    </Grid>
  );
}

Upvotes: 0

SakisTsalk
SakisTsalk

Reputation: 875

Like my comment above try:

onClick={() => console.log(params.row._id)}

instead of

onClick={console.log(params.row._id)}

You have to return an arrow function inside the onClick event handler.

Upvotes: 1

Related Questions