5

I am using the react-table library to create a table with filterable columns. The table is of the following format:

const defaultFilter = [{
  id: 'title',
  value: '',
}];

const ExampleTable = ({ documents, filter = defaultFilter }) => {
  const columns = [
    {
      accessor: 'title',
      filterable: true,
      id: 'title',
      width: 375,
      Cell: props => {
        return (
          <div>
            { props.value }
          </div>
        );
      },
      Filter: ({ filter, onChange }) => (
        <input
          onChange={ event => onChange(event.target.value) }
          style={ { width: '100%' } }
          placeholder={ 'Enter Filter' }
          value={ filter ? filter.value : '' }
        />
      ),
      filterMethod: (filter, row, column) => (row.title.toLowerCase().includes(filter.value.toLowerCase())),
      Header: () => (
        <span>
          Column Header
        </span>
      ),
    }
  ];

  return (
    <ReactTable
      columns={ columns }
      data={ documents } // an array of objects
      manual={ true }
      filtered={ filter }
      onFilteredChange={
        (filteredColumns, value) => {
          Store.updateFilter(filteredColumns);
        }
      }
    />
  );
};

Whenever I type into the input element created by the Filter attribute of my single column, a callback is made to my flux store that updates the filter, of which gets passed back into my stateless table component. However, upon this specific action, the filter input gets recreated, and the input consequently loses focus as a result.

Thus, I'd have to manually put the focus back onto the input each time. Might there be a better way of maintaining the reference to that input, so that React doesn't recreate the input every time the props change?

Xenyal
  • 2,136
  • 2
  • 24
  • 51
  • Did you ever solve this issue? I'm having the same problem... – Jessica Mar 30 '20 at 15:17
  • @Jessica I have yet to find a good solution. A monkey patch for this is to use a ref on the input such that when the user types into the text input, we focus back into it after passing the updated value. Do note that my problem is in `react-table` versions 6.x.x – Xenyal Mar 30 '20 at 15:21
  • I'm using 7, but still getting the issue... Gonna try the patch – Jessica Mar 30 '20 at 15:37

0 Answers0