Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Add demo for single click edit #2186

Closed
1 task done
Tracked by #5744
oliviertassinari opened this issue Jul 22, 2021 · 23 comments · Fixed by #8365
Closed
1 task done
Tracked by #5744

[DataGrid] Add demo for single click edit #2186

oliviertassinari opened this issue Jul 22, 2021 · 23 comments · Fixed by #8365
Labels
component: data grid This is the name of the generic UI component, not the React module! docs Improvements or additions to the documentation feature: Editing Related to the data grid Editing feature new feature New feature or request waiting for 👍 Waiting for upvotes

Comments

@oliviertassinari
Copy link
Member

oliviertassinari commented Jul 22, 2021

  • I have searched the issues of this repository and believe that this is not a duplicate.

Summary 💡

Add demo for single-click edit.

https://mui.com/components/data-grid/editing/.

Examples 🌈

https://codesandbox.io/s/material-demo-forked-3s7y6?file=/demo.tsx

https://codesandbox.io/s/material-demo-forked-9zq44?file=/demo.tsx

export default function StartEditButtonGrid() {
  const [cellModesModel, setCellModesModel] = React.useState<
    GridCellModesModel
  >({});

  const handleCellClick = React.useCallback((params: GridCellParams) => {
    setCellModesModel((prevModel) => {
      return {
        // Revert the mode of the other cells from other rows
        ...Object.keys(prevModel).reduce(
          (acc, id) => ({
            ...acc,
            [id]: Object.keys(prevModel[id]).reduce(
              (acc2, field) => ({
                ...acc2,
                [field]: { mode: GridCellModes.View }
              }),
              {}
            )
          }),
          {}
        ),
        [params.id]: {
          // Revert the mode of other cells in the same row
          ...Object.keys(prevModel[params.id] || {}).reduce(
            (acc, field) => ({ ...acc, [field]: { mode: GridCellModes.View } }),
            {}
          ),
          [params.field]: { mode: GridCellModes.Edit }
        }
      };
    });
  }, []);

  const handleCellModesModelChange = React.useCallback((newModel) => {
    setCellModesModel(newModel);
  }, []);

  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        cellModesModel={cellModesModel}
        onCellModesModelChange={handleCellModesModelChange}
        onCellClick={handleCellClick}
        experimentalFeatures={{ newEditingApi: true }}
      />
    </div>
  );
}

Motivation 🔦

This is a popular configuration, from one of our users:

Can we make all the fields in the table always editable? Right now, we have to double-click into a field before we can edit it, which is not the ideal user experience.

or https://www.ag-grid.com/react-grid/cell-editing/#single-click-editing

@oliviertassinari oliviertassinari added docs Improvements or additions to the documentation new feature New feature or request waiting for 👍 Waiting for upvotes labels Jul 22, 2021
@dtassone
Copy link
Member

@oliviertassinari
Copy link
Member Author

Ok great, to use as inspiration and to remove from the storybook once we move it to the docs.

@m4theushw
Copy link
Member

Can we make all the fields in the table always editable?

I wonder if the user is not asking for the row editing here.

Add demo for single-click edit.

We have to disable the selection on click or stop the propagation:

<XGrid
  rows={rows}
  columns={columns}
  apiRef={apiRef}
  disableSelectionOnClick
  onCellClick={handleCellClick}
/>

@AnotherHermit
Copy link

We are trying to use this pattern but run into a small issue that is also present in the code sandbox example, namely that clicking on an editable cell from the edit mode of another editable cell doesn't reset the first cell to view mode. Is there a simple workaround for this?
For the single select and our custom date selector I manually reset the cell in the "onCellEditCommit" handler, but that handler does not seem to run at all for the standard editing elements (apart from single select) when clicking on another editable cell.

@AnotherHermit
Copy link

AnotherHermit commented Oct 19, 2021

In case someone else has the same issue we had with the single click edits, we solved it by adding an on blur handler to the specific inputs that didn't exit edit mode when another field was focused. This is the onBlur handler we used:

const handleBlur = ({ id, field, api }: GridRenderEditCellParams) => {
  api?.commitCellChange({ id, field });
  api?.setCellMode(id, field, 'view');
};

// In the column definition for column using the string and number type we added:
renderEditCell: params =>
  renderEditInputCell({
    ...params,
    onBlur: () => handleBlur(params),
  }),

@m4theushw
Copy link
Member

@AnotherHermit I took a look at the problem you mentioned and it's happening because internally, when apiRef.current.setCellMode is called it updates which cell is focused, however, the click is also used to update the focused cell. Having both updating the state doesn't work correctly. With the double-click to edit, the same issue can't be seen as the first click updates the focus, then the second click triggers the edit mode. I updated the issue description with a better solution involving disabling the default behavior.

@OuiameEngineer
Copy link

Thank you @AnotherHermit you save my project with your post :

renderEditCell: params =>
  renderEditInputCell({
    ...params,
    onBlur: () => handleBlur(params),
  }),

It works very good for advanced edition in mui ReactJS 👍 , i need this code to init a state, to get the api object, so i can update value in the DataGrid after a modal call, for my case i do like this :

renderEditCell: params => setClientGroupApi(params.api),

@oliviertassinari oliviertassinari added feature: Editing Related to the data grid Editing feature component: data grid This is the name of the generic UI component, not the React module! labels Jan 29, 2022
@colespencer1453
Copy link

@m4theushw Single click editing would be an awesome feature to control through a boolean prop flag. Seems like it would be a pretty common use case. As a user I hate having to click twice for an action I need to take frequently.

@BarneyWhiteman
Copy link

I agree with @colespencer1453, implementing single click editing is a pain but seems like something that should be handled out of the box as a simple flag on the props.

@colespencer1453
Copy link

@oliviertassinari The demo you originally posted here works fine for the old editing api, is there any chance someone from the team could post a working example of single click editing with the new editing api?

@m4theushw
Copy link
Member

I updated the demo to use the new editing API. Now it also works with the MIT version of the DataGrid. It was based on https://mui.com/x/react-data-grid/editing/#controlled-mode

@colespencer1453
Copy link

@m4theushw Thank you!!

@cjauvin
Copy link

cjauvin commented Nov 14, 2022

Thanks a lot for this, it's really helpful, and I too would like to cast my vote in favor of the eventual inclusion of this feature in the official version, as it seems to me that having to double-click on a UI control is not as expected, nowadays, as it once was, and especially in the context of a web app.

In my context however, some columns are editable, but not all, and so here is how I had to adapt the code in my context, if it might be useful to anyone:

import { DataGrid, DataGridProps, GridCellModes, GridCellModesModel, GridCellParams } from "@mui/x-data-grid"
import React from "react"

export default function DataGridWithSingleClickCellEdit(props: DataGridProps) {
  const [cellModesModel, setCellModesModel] = React.useState<GridCellModesModel>({})

  const handleCellClick = React.useCallback((params: GridCellParams) => {
    if (params.isEditable) {
      setCellModesModel(prevModel => {
        return {
          // Revert the mode of the other cells from other rows
          ...Object.keys(prevModel).reduce(
            (acc, id) => ({
              ...acc,
              [id]: Object.keys(prevModel[id]).reduce(
                (acc2, field) => ({
                  ...acc2,
                  [field]: { mode: GridCellModes.View }
                }),
                {}
              )
            }),
            {}
          ),
          [params.id]: {
            // Revert the mode of other cells in the same row
            ...Object.keys(prevModel[params.id] || {}).reduce(
              (acc, field) => ({ ...acc, [field]: { mode: GridCellModes.View } }),
              {}
            ),
            [params.field]: { mode: GridCellModes.Edit }
          }
        }
      })
    }
  }, [])

  const handleCellModesModelChange = React.useCallback(newModel => {
    setCellModesModel(newModel)
  }, [])

  return (
    <DataGrid
      cellModesModel={cellModesModel}
      onCellModesModelChange={handleCellModesModelChange}
      onCellClick={handleCellClick}
      experimentalFeatures={{ newEditingApi: true }}
      {...props}
    />
  )
}

Note that this component can be used as a drop-in replacement for a normal DataGrid.

@m4theushw m4theushw moved this to 🆕 Needs refinement in MUI X Data Grid Nov 17, 2022
@m4theushw m4theushw moved this from 🆕 Needs refinement to 🔖 Ready in MUI X Data Grid Nov 17, 2022
@laveena-pahuja
Copy link

laveena-pahuja commented Mar 7, 2023

  • I have searched the issues of this repository and believe that this is not a duplicate.

Summary 💡

Add demo for single-click edit.

https://mui.com/components/data-grid/editing/.

Examples 🌈

https://codesandbox.io/s/material-demo-forked-3s7y6?file=/demo.tsx

https://codesandbox.io/s/material-demo-forked-9zq44?file=/demo.tsx

export default function StartEditButtonGrid() {
  const [cellModesModel, setCellModesModel] = React.useState<
    GridCellModesModel
  >({});

  const handleCellClick = React.useCallback((params: GridCellParams) => {
    setCellModesModel((prevModel) => {
      return {
        // Revert the mode of the other cells from other rows
        ...Object.keys(prevModel).reduce(
          (acc, id) => ({
            ...acc,
            [id]: Object.keys(prevModel[id]).reduce(
              (acc2, field) => ({
                ...acc2,
                [field]: { mode: GridCellModes.View }
              }),
              {}
            )
          }),
          {}
        ),
        [params.id]: {
          // Revert the mode of other cells in the same row
          ...Object.keys(prevModel[params.id] || {}).reduce(
            (acc, field) => ({ ...acc, [field]: { mode: GridCellModes.View } }),
            {}
          ),
          [params.field]: { mode: GridCellModes.Edit }
        }
      };
    });
  }, []);

  const handleCellModesModelChange = React.useCallback((newModel) => {
    setCellModesModel(newModel);
  }, []);

  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        cellModesModel={cellModesModel}
        onCellModesModelChange={handleCellModesModelChange}
        onCellClick={handleCellClick}
        experimentalFeatures={{ newEditingApi: true }}
      />
    </div>
  );
}

Motivation 🔦

This is a popular configuration, from one of our users:

Can we make all the fields in the table always editable? Right now, we have to double-click into a field before we can edit it, which is not the ideal user experience.

or https://www.ag-grid.com/react-grid/cell-editing/#single-click-editing

After performing the single-click-edit on cell the problem arises when we apply it with treeData or rowGrouping and when we expand the children and perform the single-click-editing the row collapses and we are not able to edit the children.

@MBilalShafi MBilalShafi moved this from 🔖 Ready to 🏗 In progress in MUI X Data Grid Mar 24, 2023
@tyukesz
Copy link

tyukesz commented Mar 29, 2023

This feature should be enabled by a prop, not with some demo/workaround.

@laveena-pahuja
Copy link

laveena-pahuja commented Mar 29, 2023 via email

@DannyMeister
Copy link

I ran into an issue with the code sample that if the cell editing were initiated by an api call to startCellEditMode() which passed in an initialValue, that this single-click edit grid would ignore the initialValue. The following fork of the sandbox fixes that issue (and includes @cjauvin 's isEditable fix ) with the following line in handleCellClick:

...(prevModel[params.id] || {})[params.field],

https://codesandbox.io/s/material-demo-forked-c0ldcq?file=/demo.tsx

@m4theushw
Copy link
Member

I ran into an issue with the code sample that if the cell editing were initiated by an api call to startCellEditMode() which passed in an initialValue, that this single-click edit grid would ignore the initialValue.

@DannyMeister How can I reproduce this bug? I called startCellEditMode with an initial value and the new value was kept.

@Nick-Zag
Copy link

Hello! After I called startCellEditMode, I can't stop editing mode by clickin 'Enter', only by clicking the same icon which fires editing mode

export const NotesCellRenderer = () => {
  const apiRef = useGridApiContext();
  const [editMode, setEditMode] = useState<boolean>(false);
 
  return (
    <Icon
      icon={editMode ? 'times' : 'edit'}
      onClick={() => {
        if (editMode) {
          apiRef.current.stopCellEditMode({
            id: apiRef.current.state.tabIndex?.cell?.id!,
            field: 'note',
            ignoreModifications: true,
          });
          setEditMode(!editMode);
        } else {
          apiRef.current.startCellEditMode({ id: apiRef.current.state.tabIndex?.cell?.id!, field: 'note' });
          setEditMode(!editMode);
        }
      }}
    />
  );
};

@cherniavskii cherniavskii moved this from 🏗 In progress to 👀 In review in MUI X Data Grid Jun 20, 2023
@cherniavskii cherniavskii moved this from 👀 In review to ✅ Done in MUI X Data Grid Jun 20, 2023
@m4theushw
Copy link
Member

@Nick-Zag Could you create another issue with the complete example?

@TheaCatW
Copy link

Has anyone tried this feature with grouping? I can't seem to make child items editable work. The single click edit only applies to parent row but not child.

@eschneor

This comment was marked as resolved.

@gulicJan
Copy link

gulicJan commented Apr 17, 2024

Has anything been done to support single-click edit with treeData or rowGrouping? - When we expand the children and perform the single-click-editing the row collapses and we are not able to edit the children.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: data grid This is the name of the generic UI component, not the React module! docs Improvements or additions to the documentation feature: Editing Related to the data grid Editing feature new feature New feature or request waiting for 👍 Waiting for upvotes
Projects
Status: Done
Development

Successfully merging a pull request may close this issue.