Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the all-in-one-seo-pack domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/fes/web/olgamatosova.sfdevserver.com/public_html/blog/wp-includes/functions.php on line 6121

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wp-diary domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/fes/web/olgamatosova.sfdevserver.com/public_html/blog/wp-includes/functions.php on line 6121
How To Connect MUI DATAGRID With Date Range filter -

How To Connect MUI DATAGRID With Date Range filter

How To Connect MUI DATAGRID With Date Range filter

Probably, each react developer encountered with non effective documentation for different libraries. And spent a lot of time to achievement desired result.
In this article, I will guide you through the process of adding a custom DateRange component into the MUI DataGrid, allowing users to filter by date ranges. We’ll be using the DateRange component from the react-date-range library and integrating it into the DataGrid’s column settings

Step 1: First, ensure you have the required libraries installed in your project. You’ll need both MUI DataGrid and react-date-range

npm install --save @mui/x-data-grid react-date-range


Step 2: Create DateFilterComponent and import DateRange and styles into your component:

Your custom date range filter component should handle how the date filter is displayed and function.

import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'
import { DateRange } from 'react-date-range';
<DateRange
     editableDateInputs={true}
     onChange={handleFilterChange}
     moveRangeOnFirstSelection={false}
     ref={dateRangeRef}
     ranges={state}
/>

Also for formatting dates let’s setup datajs

npm install dayjs
import * as dayjs from 'dayjs';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css';
import { DateRange } from 'react-date-range';

export function DateFilterComponent(props) {
    const { item, applyValue } = props;
    const [state, setState] = useState(
        [
            {
                startDate: new Date(),
                endDate: new Date(),      
                key: "selection"
           }
        ]);

    const dateRangeRef = useRef(null);
    const handleFilterChange = (value) => {    
        applyValue({      
            ...item,      
            value: `${dayjs(value.selection.startDate).format("DD-MM-YYYY")}/${dayjs(value.selection.endDate).format("DD-MM-YYYY")}`
        });    
        setState([value.selection]);  
    };
    return(
       <DateRange
          editableDateInputs={true}
          onChange={handleFilterChange}
          moveRangeOnFirstSelection={false}
          ref={dateRangeRef}
          ranges={state}
       />
    )
}

Key Concepts:

  1. Importing Dependencies:
    • The code imports dayjs for date manipulation and formatting.
    • Stylesheets for react-date-range are imported to ensure the component displays correctly.
  2. Component Structure:
    • The component receives item and applyValue as props, which are used to apply the selected date range filter.
    • useState manages the selected date range, initializing both startDate and endDate to the current date.
    • useRef creates a reference to the DateRange component, allowing for direct interaction with the date picker.
  3. Handling Date Selection:
    • The handleFilterChange function formats the selected date range using dayjs, applying it in the “DD-MM-YYYY” format.
    • This function also updates the component’s state with the new date range whenever the user makes a selection.
  4. Rendering the Date Range Picker:
    • The DateRange component from react-date-range is rendered with the ability to edit the date inputs.
    • The selected date range is displayed and updated as the user interacts with the picker.

This component integrates a date range filter in a custom way, making it a valuable addition for implementing advanced filters in MUI DataGrid.

Step 3: Set up filterOperators for the date column: The filterOperators prop allows you to customize the operators for a specific column. You will apply the date filter operators using getGridDateOperators() and integrate it with the custom DateFilterComponent

  const columns = [
      {
        field: "created_at",
        headerName: "Date account created",
        type: "date",
        filterOperators: getGridDateOperators()
          .filter((operator) => operator.value == "is")
          .map((operator) => {
            return {
              ...operator,
              InputComponent: DateFilterComponent,
              InputComponentProps: { type: "date" },
            };
          }),
      }
    ];
<DataGrid
    columns={columns}
    rows={membersList}
    onSortModelChange={onSortChange}
    slots={{
       toolbar: CustomToolbar,
    }}
/>

Back To Top