javascriptmaterial-uimaterial-table

How to clear the column filter cell in Material-Table?


I am using this TextField to create a custom filter cell for each column in my Material-Table.

I want to use the endAdornment as a button to clear the filter, but I have no way of removing the value.

filterComponent: ({ columnDef, onFilterChanged }) => (
    <TextField
        onChange={(e) => {
            onFilterChanged(columnDef.tableData.id, e.target.value);
        }}
        InputProps={{
            startAdornment: (
                <InputAdornment position="start">
                    <FilterList />
                </InputAdornment>
            ),
            endAdornment: (
                <InputAdornment position="end">
                    <IconButton>
                        <Clear className={classes.endAdornment} />
                    </IconButton>
                </InputAdornment>
            ),
        }}
    />
),

Solution

  • Based on the piece of code you provided, I see that you set the filters via the following function. Which takes the columnID and value

    onFilterChanged(columnDef.tableData.id, e.target.value);
    

    Maybe you can put this on the IconButton component as well

    endAdornment: (
                    <InputAdornment position="end">
                        <IconButton onClick={() => onFilterChanged(columnDef.tableData.id, '')}>
                            <Clear className={classes.endAdornment} />
                        </IconButton>
                    </InputAdornment>
                ),
    

    LE: with controlled value

    filterComponent: ({ columnDef, onFilterChanged }) => (
        <TextField
            value={columnDef.tableData.filterValue}
            onChange={(e) => {
                onFilterChanged(columnDef.tableData.id, e.target.value);
            }}
            InputProps={{
                startAdornment: (
                    <InputAdornment position="start">
                        <FilterList />
                    </InputAdornment>
                ),
                endAdornment: (
                    <InputAdornment position="end">
                        <IconButton onClick={() => onFilterChanged(columnDef.tableData.id, '')}>
                            <Clear className={classes.endAdornment} />
                        </IconButton>
                    </InputAdornment>
                ),
            }}
        />
    ),