Search code examples
javascriptreactjsmaterial-uimaterial-table

How to change the filtered date format in material table react?


In material table react, I have the following columns:

columns={[
            {
              title: 'Name',
              field: 'name',
              type: 'string',
            },
            {
              title: 'Age',
              field: 'age',
              type: 'string',
            },
            {
              title: 'DOB',
              field: 'birthDate',
              type: 'date',
              dateSetting: {
                format: 'dd/MM/yyyy'
              },
            }
         ]}

When I try to filter the date column it shows filtered date as, for example, February 24th, but instead I want the date to be like dd/MM/yyyy format.

How can I change the value. I already tried giving dateSetting, but it does not work on filter. Thank You.


Solution

  • You could achieve that by defining your own filterComponent. Here is a working example I made based on this solution:

    enter image description here

    First, you need to create the component to be used as a filter, in my case I used KeyboardDatePicker from material-ui/pickers, but could it be anything you need:

    
    const CustomDatePicker = (props) => {
      const [date, setDate] = useState(null);
    
      return (
        <MuiPickersUtilsProvider utils={DateFnsUtils}>
          <KeyboardDatePicker
            margin="normal"
            id="date-picker-dialog"
            label="Date picker"
            format="dd/MM/yyyy"
            clearable
            value={date}
            onChange={(event) => {
              console.log("Date picker value: ", event);
              console.log(props.columnDef.tableData.id);
    
              setDate(event);
              props.onFilterChanged(props.columnDef.tableData.id, event);
            }}
            KeyboardButtonProps={{
              "aria-label": "change date"
            }}
          />
        </MuiPickersUtilsProvider>
      );
    };
    

    The key aspect is to call the onFilterChanged function that is passed via props.

    Then, on your column definition just implement your component, like this:

     const tableColumns = [
        { title: "Client", field: "id" },
        { title: "Name", field: "name" },
    
        {
          title: "Date",
          field: "date",
          type: "date",
          dateSetting: { locale: "en-GB" },
          filterComponent: (props) => <CustomDatePicker {...props} />
        }
      ];
    

    Full code and sandbox here. Hope that works for you!