Material React Table V2 - Global Filtering by date - Problem

199 Views Asked by At

I have been studying the component library and it looks quite complete. The issue is that in my projects I use global filtering by date a lot. And I see that it doesn't even work in the examples on the page (https://www.material-react-table.com/docs/examples/advanced). Can anyone give me a hand on how to use the global filter for the date columns.

import { useMemo, useState  } from 'react';
import {
  MaterialReactTable,
 // createMRTColumnHelper,
  useMaterialReactTable,
} from 'material-react-table';
import { Box, Button, Typography, Menu, MenuItem } from '@mui/material';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { mkConfig, generateCsv, download } from 'export-to-csv'; //or use your library of choice here
import data from './makeData';
import '../../App.css'

//const columnHelper = createMRTColumnHelper();
//nested data is ok, see accessorKeys in ColumnDef below
  


const csvConfig = mkConfig({

    fieldSeparator: ',',
  
    decimalSeparator: '.',
  
    useKeysAsHeaders: true,
  
  });
  
  

const Datatables = () => {

    const [anchorEl, setAnchorEl] = useState(null);

    const handleOpenMenu = (event) => {
        setAnchorEl(event.currentTarget);
      };
    
      const handleCloseMenu = () => {
        setAnchorEl(null);
      };



    const handleExportRows = (rows) => {

        const rowData = rows.map((row) => row.original);
    
        const csv = generateCsv(csvConfig)(rowData);
    
        download(csvConfig)(csv);
    
      };
    
    
      const handleExportData = () => {
    
        const csv = generateCsv(csvConfig)(data);
    
        download(csvConfig)(csv);
    
      };



  //should be memoized or stable
  const columns = useMemo(
    () => [{
        accessorKey:'id',
        header: 'ID',
        size: 40,
        enableColumnFilter:false,
      },
      {       
        accessorKey:'first_name', //access nested data with dot notation
        header: 'First Name',
        size: 50,
        filterFn:'contains',
      },
      {
        accessorKey: 'last_name',
        header: 'Last Name',
        size: 50,
        filterFn:'contains',
      },
      {
        accessorKey: 'address', //normal accessorKey
        header: 'Address',
        size: 200,
        filterFn:'contains',
      },
      {
        accessorKey: 'city',
        header: 'City',
        size: 150,
        filterFn:'contains',
      },
      {
        accessorKey: 'state',
        header: 'State',
        size: 150,
        filterFn:'contains',
      },
      {
        accessorFn: (originalRow) => new Date(originalRow.birth), // Convertir a objeto de fecha
        id: 'birth',
        header: 'Cumpleaños',
        filterVariant: 'date',
        filterFn: 'contains', // Utilizar la función de filtro 'contains' para permitir la búsqueda de fechas
        Cell: ({ cell }) => {
        // Agregar console.log para depuración
        console.log('Valor de la celda:', cell.getValue());
        const formattedDate = cell.getValue().toLocaleDateString(); // Convertir de nuevo a cadena para mostrar
        console.log('Fecha formateada:', formattedDate);
        return formattedDate;
        },
        size: 150,
      },
      {
        accessorFn: (originalRow) => new Date(originalRow.access), //convert to date for sorting and filtering
        id: 'access',
        header: 'Arrival Time',
        filterVariant: 'datetime',
        Cell: ({ cell }) =>
          `${cell.getValue().toLocaleDateString()} ${cell
            .getValue()
            .toLocaleTimeString()}`, // convert back to string for display
             size: 150,
      },      
    ],
    [],
  );

  const table = useMaterialReactTable({
    columns,
    data, //data must be memoized or stable (useState, useMemo, defined outside of this component, etc.)
    initialState: {
      showGlobalFilter: true, //show the global filter by default
    },
    filterFn: 'contains',    
    enableGlobalFilterModes: true,
    enableGlobalFilter: true,
    globalFilterModeOptions: ['contains'],
    enableRowSelection: true,
    paginationDisplayMode: 'pages',
    muiPaginationProps: {
        shape: 'rounded',
        showRowsPerPage: true,
      },
    enableSorting: true,
    positionToolbarAlertBanner: 'bottom',
    enableDensityToggle: false,
    enableColumnFilterModes: true,
    globalFilterFn: 'contains',
    showGlobalFilter: true,
   /* enableRowVirtualization: true,
    rowVirtualizerOptions: { overscan: 5 }, //optionally customize the row virtualizer
    columnVirtualizerOptions: { overscan: 2 }, //optionally customize the column virtualizer*/
    defaultColumn: {
        minSize: 20, //allow columns to get smaller than default
        maxSize: 9001, //allow columns to get larger than default
        size: 300, //make columns wider by default
      },
    renderTopToolbarCustomActions: ({ table }) => (
        
        <Box
        sx={{
          display: 'flex',
          gap: '16px',
          padding: '8px',
          flexWrap: 'wrap',
        }}
      >
        <Typography variant="h5">Listado de Usuarios</Typography>
        <Button onClick={handleOpenMenu} startIcon={<FileDownloadIcon />}>
          Exportar
        </Button>
        <Menu
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={handleCloseMenu}
        >
          <MenuItem onClick={handleExportData}>Exportar Todos los Datos</MenuItem>
          <MenuItem 
            disabled={table.getPrePaginationRowModel().rows.length === 0}
            onClick={() => handleExportRows(table.getPrePaginationRowModel().rows)}
          >
            Exportar Todas las Filas
          </MenuItem>
          <MenuItem
            disabled={table.getRowModel().rows.length === 0}
            onClick={() => handleExportRows(table.getRowModel().rows)}
          >
            Exportar Filas de la Página
          </MenuItem>
          <MenuItem
            disabled={!table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected()}
            onClick={() => handleExportRows(table.getSelectedRowModel().rows)}
          >
            Exportar Filas Seleccionadas
          </MenuItem>
        </Menu>
      </Box>
  
      ),
  });

  console.log('Valor del filtro global:', table.options.state.globalFilter);
  
  return (
    <Box sx={{ maxWidth: '100%' }}>
        <MaterialReactTable table={table} />
    </Box>

  );    

};

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import 'dayjs/locale/es-mx.js';

const ExampleWithLocalizationProvider = () => (
  //App.tsx or AppProviders file
  <LocalizationProvider dateAdapter={AdapterDayjs}  adapterLocale="es-mx">
    <Datatables />
  </LocalizationProvider>
);

export default ExampleWithLocalizationProvider;

In the code I put some "console.log" to check the date format. Even so, it does not perform the Globalfilter.

0

There are 0 best solutions below