Data-Grid events firing on init and not after

1.8k Views Asked by At

Background: Hello, I am using React with the latest MUI version of Material-UI. I am using Data-Grid in a separate file in my components folder. I call the component from my App and use states to handle adding rows. On init 50 rows are added.

Issue: When I add onRowEditStart={console.log("Start")} & onRowEditStop={console.log("stop")} to the DataGrid component, they are only fired on page load, but if I edit a column after, no events are fired?

Whole components/DataGrid.js added.

If anyone has info on this would be great, thanks!

import * as React from 'react';
import { DataGrid, GridToolbar } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';

export default function Table(props) {

const [rows, setRows] = React.useState(props.rows);

React.useEffect(() => {
    setRows(props.rows);
  }, [props.rows]);

  return (
    <div style={{ width: '100%' }}>
      <Stack
        sx={{ width: '100%', mb: 1 }}
        direction="row"
        alignItems="flex-start"
        columnGap={1}
      >
      </Stack>
      <Box sx={{ height: 400, bgcolor: 'background.paper' }}>
        <DataGrid autoHeight 
        components={{
            Toolbar: GridToolbar,
        }}
        pageSize={25}
        rowsPerPageOptions={[25, 50, 100]}
        onRowEditStart={console.log("Start")}
        onRowEditStop={console.log("stop")}
        experimentalFeatures={{ newEditingApi: true }}
        rows={rows} 
        columns={props.columns} 
        loading={props.rows.length === 0}
        columnGap={1}
        rowHeight={75}
        />
      </Box>
    </div>
  );
}
1

There are 1 best solutions below

2
On

The reason for this is because both onRowEditStart and onRowEditStop accept functions.

If you replace your code with the following, it will work.

onRowEditStart={() => console.log("Start")}
onRowEditStop={() => console.log("stop")}

Notice the difference in your code.

onRowEditStart={console.log("Start")} // evaluated on page load
onRowEditStop={console.log("stop")} // evaluated on page load

By passing a function (onRowEditStart={() => console.log("Start")}), the console.log("Start") will only be run when a row edit has started.