Home > Software engineering >  Retrieving value from row on click on button in grid React MUI
Retrieving value from row on click on button in grid React MUI

Time:11-26

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>
  );
}

CodePudding user response:

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.

Glad that your code works now, happy coding :)

  • Related