admin管理员组文章数量:1435809
I have created a table with material-react-table, where rows can be selected and exported in a PDF, I would like if these rows are filtered (for example, quantity greater than 5000) be able to get these filters and then be able to show them in the PDF and that can be understood in context of the data.
I tried creating a columnFilters state, and then using the onColumnFiltersChange library function, setting the new filters, this worked, but the result shows only the filter value, but not the filter name.
import React, { useEffect, useState } from "react";
import { Delete } from "@mui/icons-material";
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { Box, Button, ListItemIcon, MenuItem, lighten } from "@mui/material";
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import {
MRT_GlobalFilterTextField,
MRT_ToggleFiltersButton,
MaterialReactTable,
useMaterialReactTable,
} from "material-react-table";
import { MRT_Localization_ES } from "material-react-table/locales/es";
const MovementsTable = ({ movements, commodities, handleOpenDeleteModal }) => {
const [columnFilters, setColumnFilters] = useState([]);
const columns = [
{
id: "created_at",
header: "Fecha",
columns: [
{
accessorFn: (row) =>
new Date(row.created_at).toLocaleDateString("es-ES", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}),
id: "created_at",
header: "Fecha",
size: 250,
},
],
},
{
id: "movement_id",
header: "Movimiento Nº",
columns: [
{
accessorFn: (row) => `${row.movement_id}`,
id: "movement_id",
header: "Movimiento Nº",
size: 250,
},
],
},
{
id: "form_number",
header: "Formulario Nº",
columns: [
{
accessorFn: (row) => `${row.form_number}`,
id: "form_number",
header: "Formulario Nº",
size: 250,
},
],
},
{
id: "commodity",
header: "Producto",
columns: [
{
accessorFn: (row) =>
`${commodities[rowmodity] || "Producto Desconocido"}`,
id: "commodity",
header: "Producto",
size: 250,
},
],
},
{
id: "quantity",
header: "Cantidad [kg]",
columns: [
{
accessorFn: (row) => `${row.quantity}`,
id: "quantity",
header: "Cantidad [kg]",
size: 250,
},
],
},
{
id: "origin_destination",
header: "Origen/Destino",
columns: [
{
accessorFn: (row) =>
`${row.movement_type === "input" ? "Ingreso desde " + row.origin : "Salida hacia " + row.destination}`,
id: "origin_destination",
header: "Origen/Destino",
size: 250,
},
],
},
{
id: "observations",
header: "Observaciones",
columns: [
{
accessorFn: (row) => `${row.observations}`,
id: "observations",
header: "Observaciones",
size: 250,
},
],
},
];
const handleExportRows = (rows) => {
const doc = new jsPDF('landscape');
// Mapear las filas a los valores de las columnas
const tableData = rows.map((row) => {
return columns.map((column) => {
return column.columns[0].accessorFn(row.original) || '';
})
});
// Obtener los encabezados de las columnas
const tableHeaders = columns.map((column) => {
return column.columns[0].header;
});
// Crear la tabla en el PDF con los datos procesados
autoTable(doc, {
head: [tableHeaders],
body: tableData,
theme: 'grid',
headStyles: {
fillColor: [2, 129, 67],
textColor: [255],
},
});
// Guardar el reporte en PDF
const now = new Date().toLocaleDateString('es-ES', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).replace(/\//g, '-');
doc.save(`oilcan-movements-report-${now}.pdf`);
};
useEffect(() => {
console.log(columnFilters);
}, [columnFilters]);
const table = useMaterialReactTable({
columns,
data: movements,
enableColumnFilterModes: true,
enableColumnOrdering: true,
enableGrouping: true,
enableColumnPinning: true,
enableFacetedValues: true,
enableRowActions: true,
enableColumnFilterModes: true,
onColumnFiltersChange: setColumnFilters, //hoist internal columnFilters state to your state
state: { columnFilters }, //pass in your own managed columnFilters state
enableRowSelection: true,
localization: MRT_Localization_ES,
initialState: {
showColumnFilters: true,
showGlobalFilter: true,
columnPinning: {
right: ["mrt-row-actions"],
},
},
paginationDisplayMode: "pages",
positionToolbarAlertBanner: "bottom",
muiTableBodyRowProps: ({ row }) => ({
sx: {
backgroundColor:
row.original.movement_type === "input" ? "#00800075" : "#ff000078",
},
}),
muiSearchTextFieldProps: {
size: "small",
variant: "outlined",
},
muiPaginationProps: {
color: "secondary",
rowsPerPageOptions: [10, 20, 30],
shape: "rounded",
variant: "outlined",
},
renderRowActionMenuItems: ({ row, closeMenu }) => [
<MenuItem
key={0}
onClick={() => {
handleOpenDeleteModal(row.original.movement_id);
closeMenu();
}}
sx={{ m: 0 }}
>
<ListItemIcon>
<Delete />
</ListItemIcon>
Eliminar Movimiento
</MenuItem>,
],
renderTopToolbar: ({ table }) => {
return (
<Box
sx={(theme) => ({
backgroundColor: lighten(theme.palette.background.default, 0.05),
display: "flex",
gap: "0.5rem",
p: "8px",
justifyContent: "space-between",
})}
>
<Box sx={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
<MRT_GlobalFilterTextField table={table} />
<MRT_ToggleFiltersButton table={table} />
</Box>
<Button
disabled={
!table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected()
}
//only export selected rows
onClick={() => handleExportRows(table.getSelectedRowModel().rows)}
startIcon={<FileDownloadIcon />}
>
Exportar Filas Seleccionadas
</Button>
</Box>
);
},
renderTopToolbarCustomActions: ({ table }) => (
<Box
sx={{
display: 'flex',
gap: '16px',
padding: '8px',
flexWrap: 'wrap',
}}
>
<Button
disabled={table.getPrePaginationRowModel().rows.length === 0}
//export all rows, including from the next page, (still respects filtering and sorting)
onClick={() =>
handleExportRows(table.getPrePaginationRowModel().rows)
}
startIcon={<FileDownloadIcon />}
>
Export All Rows
</Button>
<Button
disabled={table.getRowModel().rows.length === 0}
//export all rows as seen on the screen (respects pagination, sorting, filtering, etc.)
onClick={() => handleExportRows(table.getRowModel().rows)}
startIcon={<FileDownloadIcon />}
>
Export Page Rows
</Button>
<Button
disabled={
!table.getIsSomeRowsSelected() && !table.getIsAllRowsSelected()
}
//only export selected rows
onClick={() => handleExportRows(table.getSelectedRowModel().rows)}
startIcon={<FileDownloadIcon />}
>
Export Selected Rows
</Button>
</Box>
),
});
return <MaterialReactTable table={table} />;
};
export default MovementsTable;
本文标签: reactjsHow to get the filters applied in a materialreacttableStack Overflow
版权声明:本文标题:reactjs - How to get the filters applied in a material-react-table? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745648610a2668286.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论