How to implement filtering logic in React table?

Viewed 17332

Im using React Table to display data I receive from an API call. Currently I save the state locally and the table displays the data. I have added filtering of column values for two columns. My filtering logic is as follows:

    <ReactTable
  data={tableData}
  noDataText="Loading.."
  filterable
  defaultFilterMethod={(filter, row) =>
    String(row[filter.id]) === filter.value}
    };
  }}
  columns={[
    {
      columns: [
        {
          Header: 'Name',
          accessor: 'Name',
          id: 'Name',
          Cell: ({ value }) => (value === 'group1' ? 
          'group1' : 'group2'),
          filterMethod: (filter, row) => {
            if (filter.value === 'all') {
              return true;
            }
            if (filter.value === 'group1') {
              return row[filter.id] === 'group1';
            }
            if (filter.value === 'group2') {
              return row[filter.id] === 'group2';
            }
          },
          Filter: ({ filter, onChange }) =>
            <select
              onChange={event => onChange(event.target.value)}
              style={{ width: '100%' }}
              value={filter ? filter.value : 'all'}
            >
              <option value="all">All</option>
              <option value="group1">Group1</option>
              <option value="group2">Group2</option>
            </select>,
        },
   }

As of now, the filtering rule is hard coded between two values. How to implement the filter logic so that the filtering is dynamic?(If there are 3 or 7 different values in a particular column, the dropdown should display all 7 values and filter should work based on any of the value selected). Since Im using React Table(https://react-table.js.org).

2 Answers

I assume you wanted to make options out of list of options. If so, here is a way you can do it:

const exampleList = ['option1','option2','option3','option4',...,'option n']

In your column:

filterMethod:  (filter, row) => customOptionsFilterMethod(filter, row),
Filter: () => ({filter, onChange}) => customOptionsFilter({filter, onChange})

Inside render() implement customOptionsFilter and customOptionsFilterMethod as:

const customOptionsFilter = ({filter, onChange}) => {
      return(
        <select
          onChange={e => onChange(e.target.value)}
          style={{  width: '100%'  }}
          value={filter ? filter.value : 'all'}
          >
          <option value='all'>Show All</option>
          {
            exampleList.map( k => {
              return <option key={k.toString()} value={k}>{k}</option>
            })
          }
        </select>
      )
    }



const customOptionsFilterMethod = (filter, row) => {

      if(filter.value === '') { return true }

      if(exampleList.includes(filter.value)){
        return row[filter.id] === filter.value
      } else { return true }

    }
Related