reactjs - How can I sort using MUI Datatable using value, instead of what's in my custom body render? - TagMerge
4How can I sort using MUI Datatable using value, instead of what's in my custom body render?How can I sort using MUI Datatable using value, instead of what's in my custom body render?

How can I sort using MUI Datatable using value, instead of what's in my custom body render?

Asked 1 years ago
1
4 answers

I found two little problems in your code.

First one: The render function in customFilterListOptions should return a string or string[] (see documentation). Second one: In the logic function of filterOptions it was necessary to convert values and filters to numbers before comparing them.

If you have any questions, let me know.

This shall work now:

import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import { TextField, FormLabel, FormGroup } from "@material-ui/core";
import { toNumber } from "lodash";

import "./styles.css";

const TEMPERATURE_PREFIX = "° C";

function App() {
  const columns = [
    {
      name: "city",
      label: "City",
      options: {
        filter: true,
        sort: false
      }
    },
    {
      name: "temp",
      label: "Temperature",
      options: {
        sort: true,
        customBodyRender: value => {
          return value + TEMPERATURE_PREFIX;
        },
        filter: true,
        filterType: "custom",
        filterList: [],
        customFilterListOptions: {
          render: value => {
            if (value[0] && value[1]) {
              return `Min Temp: ${value[0]}, Max Temp: ${value[1]}`;
            } else if (value[0]) {
              return `Min Temp: ${value[0]}`;
            } else if (value[1]) {
              return `Max Temp: ${value[1]}`;
            }
            return [];
          },
          update: (filterList, filterPos, index) => {
            console.log(
              "customFilterListOnDelete: ",
              filterList,
              filterPos,
              index
            );

            if (filterPos === 0) {
              filterList[index].splice(filterPos, 1, "");
            } else if (filterPos === 1) {
              filterList[index].splice(filterPos, 1);
            } else if (filterPos === -1) {
              filterList[index] = [];
            }

            return filterList;
          }
        },
        filterOptions: {
          names: [],
          logic(value, filters) {
            const temperature = toNumber(
              value.replace(TEMPERATURE_PREFIX, "")
            );
            const lower = toNumber(filters[0]);
            const upper = toNumber(filters[1]);
            if (lower && upper) {
              return temperature < lower || temperature > upper;
            } else if (lower) {
              return temperature < lower;
            } else if (upper) {
              return temperature > upper;
            }
            return false;
          },
          display: (filterList, onChange, index, column) => (
            <div>
              <FormLabel>Temperature</FormLabel>
              <FormGroup row>
                <TextField
                  label="min"
                  value={filterList[index][0] || ""}
                  onChange={event => {
                    filterList[index][0] = event.target.value;
                    onChange(filterList[index], index, column);
                  }}
                  style={{ width: "45%", marginRight: "5%" }}
                />
                <TextField
                  label="max"
                  value={filterList[index][1] || ""}
                  onChange={event => {
                    filterList[index][1] = event.target.value;
                    onChange(filterList[index], index, column);
                  }}
                  style={{ width: "45%" }}
                />
              </FormGroup>
            </div>
          )
        }
      }
    }
  ];

  const data = [
    { city: "Yonkers", temp: 3 },
    { city: "Hartford", temp: 11 },
    { city: "Tampa", temp: 25 },
    { city: "Dallas", temp: 30 }
  ];

  const options = {
    filterType: "checkbox"
  };

  return (
    <div className="App">
      <MUIDataTable
        title={"Employee List"}
        data={data}
        columns={columns}
        options={options}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

(https://codesandbox.io/s/competent-kirch-uc01b)

Source: link

0

in the options add the code below.

options={{
  sort: true,
  sortOrder: { name: 'id', direction: 'desc' },
}}

Source: link

0

I am working with MUI Datatables, I have a column that tells the number of users who visited a site. Till this point everything works fine but as soon as I use custom rendering to show the percentage of change, the sorting dramatically changes. I am pretty new to React but I have done quite a lot RnD on this issue but still nothing really worked. Here's my code for column definition
const topSitesColumnsComparison = [
  {
    label: "Site Name",
    key: "site",
    options: {
      customBodyRender: (value, tableMeta) => {
        return (
          <div>
            <a className="card-url-color" href={tableMeta.rowData[1]}>
              {value}
            </a>
          </div>
        );
      },
    },
  },
  {
    label: "Site URL",
    key: "siteurl",
    sort: false,
    options: {
      display: false,
    },
  },
  {
    label: "Visits",
    key: "visits",
    options: {
      sort: true,
      sortDirection: "desc",
      customBodyRender: (value, tableMeta) => {
        return (
          <div>
            {tableMeta.rowData[3] < 0 ? (
              <div>
                <div style={{ display: "inline-block", minWidth: "45px" }}>
                  {value}{" "}
                </div>
                <span style={{ color: "#b80000", fontSize: "11px" }}>
                  {" "}
                  <FontIcon
                    style={{ verticalAlign: "bottom", fontSize: "11px" }}
                    iconName="StockDown"
                  ></FontIcon>{" "}
                  {Math.abs(Math.round(tableMeta.rowData[3] * 100) / 100)}%{" "}
                  <span></span>
                </span>
              </div>
            ) : (
              <div>
                {tableMeta.rowData[3] == 0 ? (
                  <div style={{ display: "inline-block", minWidth: "45px" }}>
                    {value}{" "}
                  </div>
                ) : (
                  <div>
                    <div style={{ display: "inline-block", minWidth: "45px" }}>
                      {value}{" "}
                    </div>
                    <span style={{ color: "#0B6623", fontSize: "11px" }}>
                      {" "}
                      <FontIcon
                        style={{ verticalAlign: "bottom", fontSize: "11px" }}
                        iconName="StockUp"
                      ></FontIcon>{" "}
                      {Math.abs(Math.round(tableMeta.rowData[3] * 100) / 100)}%{" "}
                      <span></span>
                    </span>
                  </div>
                )}
              </div>
            )}
          </div>
        );
      },
    },
  },
  {
    label: "Change",
    key: "change",
    options: {
      display: false,
    },
  },
];

Source: link

0

Merge pull request #1807 from luluhoc/master
fix typo in readme
For a simple table:
import MUIDataTable from "mui-datatables";

const columns = ["Name", "Company", "City", "State"];

const data = [
 ["Joe James", "Test Corp", "Yonkers", "NY"],
 ["John Walsh", "Test Corp", "Hartford", "CT"],
 ["Bob Herm", "Test Corp", "Tampa", "FL"],
 ["James Houston", "Test Corp", "Dallas", "TX"],
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>
Or customize columns:
import MUIDataTable from "mui-datatables";

const columns = [
 {
  name: "name",
  label: "Name",
  options: {
   filter: true,
   sort: true,
  }
 },
 {
  name: "company",
  label: "Company",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "city",
  label: "City",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "state",
  label: "State",
  options: {
   filter: true,
   sort: false,
  }
 },
];

const data = [
 { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
 { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
 { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
 { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>
On each column object, you have the ability to customize columns to your liking with the 'options' property. Example:
const columns = [
 {
  name: "Name",
  options: {
   filter: true,
   sort: false
  }
 },
 ...
];
customHeadRender is called with these arguments:
function(columnMeta: {
  customHeadRender: func,
  display: enum('true', 'false', 'excluded'),
  filter: boolean,
  sort: boolean,
  download: boolean,
  empty: boolean,
  index: number,
  label: string,
  name: string,
  print: boolean,
  searchable: boolean,
  viewColumns: boolean
}, handleToggleColumn: function(columnIndex))

Source: link

Recent Questions on reactjs

    Programming Languages