Search code examples
reactjsreact-table

react-table SelectColumnFilter when values are numbers


I've implemented the react-table demo from here.

https://codesandbox.io/s/github/tannerlinsley/react-table/tree/v7/examples/filtering

This works fine other than when the select values are numbers.

This SelectColumnFilter is the filter with the issue. You can replicate the issue by amending the makeData.js file as follows (row 19).

status:
      statusChance > 0.66
        ? 1
        : statusChance > 0.33
        ? 2
        : 3,

When you filter you get the following error due to includes not working with numbers.

rowValue.includes is not a function

    // This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
  column: { filterValue, setFilter, preFilteredRows, id },
}) {
  // Calculate the options for filtering
  // using the preFilteredRows
  const options = React.useMemo(() => {
    const options = new Set()
    preFilteredRows.forEach(row => {
      options.add(row.values[id])
    })
    return [...options.values()]
  }, [id, preFilteredRows])

  // Render a multi-select box
  return (
    <select
      value={filterValue}
      onChange={e => {
        setFilter(e.target.value || undefined)
      }}
    >
      <option value="">All</option>
      {options.map((option, i) => (
        <option key={i} value={option}>
          {option}
        </option>
      ))}
    </select>
  )
}

How can this be changes without having to adjust the server code that retrieves the information?


Solution

  • On line 374 in App.js, the filter is set to "includes" but now that it is a number, it should be changed to "equals".

    {
      Header: 'Status',
      accessor: 'status',
      Filter: SelectColumnFilter,
      filter: 'equals',
    },