Search code examples
reactjsmaterial-uimui-datatablemui-x-data-grid

Input field in MUI-datatable


Is it possible to add input fields to MUI-datatable? I want the user to be able to modify data in the MUI-datatable. However the customBodyRender does not work for me.

import MUIDataTable from "mui-datatables";
import {MuiThemeProvider} from '@material-ui/core/styles';
import TextField from '@mui/material/TextField';

const columns = [
        {
            name: 'name',
            label: translationState['label.name'],
            options: {
                sort: true,
            },
            customBodyRender: (value, tableMeta, updateValue) => {  
                return (
                    <TextField required defaultValue={value} 
                      onChange={event => updateValue(event.target.value)}
                      InputProps={{
                        readOnly: false, //I tried to make sure it is not readOnly
                      }}
                    />
                )
            }
        },... some other columns]

The field is still disabled. mui-datatables documentation

I have tried to do it based on this example.

const columns = [
      {
        name: "Name",
        options: {
          filter: false,
          customBodyRender: (value, tableMeta, updateValue) => (
            <FormControlLabel
              label=""
              value={value}
              control={<TextField value={value} />}
              onChange={event => updateValue(event.target.value)}
            />
          )
        }
      },

But I cannot make it work.

Is MUI-datatables only for displaying data? Should I use @mui/x-data-grid insted of datatables to allow user to modify data?


Solution

  • I put the closing parenthesis of options on the wrong line...

    const columns = [
        {
            name: 'name',
            label: translationState['label.name'],
            options: {
                sort: true,
            // }, closing parenthesis at the wrong line
                customBodyRender: (value, tableMeta, updateValue) => {  
                    return (
                        <TextField required defaultValue={value} 
                          onChange={event => updateValue(event.target.value)}
                          InputProps={{
                              readOnly: false,
                          }}
                        />
                    )
                }
            } // correct position of `options` closing parenthesis
        },... some other columns
    

    customBodyRender is one attribute of options, so it must be within its parentheses.