javascriptreactjsmaterial-uidatagridmui-x-data-grid

How to set checkbox to true in MUI X Data Grid in my input onChange event?


I would like to make the row selected in my usage input onChange event.

enter image description here

Columns:

const columns = [
        { field: 'part_code', headerName: 'Part Code', width: 200 },
        {
            field: 'part_usage',
            headerName: 'Usage',
            width: 150,
            renderCell: (params) => {
                return (
                    <TextField
                        type="number"
                        InputLabelProps={{
                            shrink: true
                        }}
                        defaultValue={1}
                        variant="standard"
                        onChange={() => {
                            return {
                                ...params,
                                hasFocus: true
                            };
                        }}
                    />
                );
            }
        }
]

Data Grid:

<DataGrid
                rows={data}
                columns={columns}
                getRowId={(row) => row.part_id}
                pageSize={5}
                rowHeight={38}
                rowsPerPageOptions={[5]}
                checkboxSelection
                disableSelectionOnClick
                components={{ Toolbar: CustomToolbar }}
            />

I don't have any idea how to modify Data Grid in custom events.


Solution

  • You can use selectionModel prop to achieve this.

    Example:

    let [selectionModel, setSelectionModel] = useState([])
    
    ...
    
    <DataGrid
      ...
      checkboxSelection
      selectionModel={selectionModel}
      onSelectionModelChange={newSelectionModel => {
        setSelectionModel(newSelectionModel) // Handle default Data Grid selection
      }}
    />
    

    And your onChange function:

    onChange={() => {
      setSelectionModel(selectionModel => {
        if (selectionModel.includes(params.id)) {
          return selectionModel; // return if already selected
        }
    
        return selectionModel.concat(params.id)
      })
    }}
    

    See more Controlled Selection.

    Edit hardcore-stitch-j6z7nz