Pusoy
Pusoy

Reputation: 1098

How to set checkbox to true in MUI 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.

Upvotes: 0

Views: 1769

Answers (1)

User 28
User 28

Reputation: 5158

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

Upvotes: 1

Related Questions