Guest User

Multi react-select with react-table filter

a guest
Sep 28th, 2019
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import Select from 'react-select';
  3. import ReactTable from 'react-table';
  4. import 'react-table/react-table.css';
  5.  
  6. const data = [
  7.   {author: 'Terry Pratchett', title: 'Snuf'},
  8.   {author: 'Terry Pratchett', title: 'Carpe Jugulum'},
  9.   {author: 'Neil Gaiman', title: 'Good Omens'},
  10.   {author: 'Orson Scott Card', title: `Enders Game`}
  11. ];
  12.  
  13. const selectOptions = [
  14.   {value: '', label: 'Show all'},
  15.   {value: 'Terry Pratchett', label: 'Terry Pratchett'},
  16.   {value: 'Orson Scott Card', label: 'Orson Scott Card'},
  17.   {value: 'Neil Gaiman', label: 'Neil Gaiman'}
  18. ];
  19.  
  20. const multiSelectOptions = [
  21.   {value: 'Terry Pratchett', label: 'Terry Pratchett'},
  22.   {value: 'Orson Scott Card', label: 'Orson Scott Card'},
  23.   {value: 'Neil Gaiman', label: 'Neil Gaiman'}
  24. ];
  25.  
  26. function App() {
  27.   const columns = [
  28.     {
  29.       Header: 'Author',
  30.       accessor: 'author',
  31.       Filter: ({filter, onChange}) => (
  32.         // FOR SINGLE SELECT
  33.         //
  34.         // <Select
  35.         //   options={selectOptions}
  36.         //   menuPortalTarget={document.body}
  37.         //   onChange={opt => onChange(opt.value)}
  38.         // />
  39.  
  40.         // FOR MULTI SELECT
  41.         //
  42.         <Select
  43.           options={multiSelectOptions}
  44.           onChange={opt => {
  45.             onChange(opt);
  46.           }}
  47.           menuPortalTarget={document.body}
  48.           isMulti
  49.         />
  50.       ),
  51.       filterAll: true,
  52.       filterMethod: (filter, rows, column) => {
  53.         // FOR SINGLE SELECT
  54.         //
  55.         //return rows.filter(element => element.author === filter.value);
  56.  
  57.         // FOR MULTI SELECT
  58.         //
  59.         if(!filter.value || filter.value.length === 0) return rows;
  60.         const authors = filter.value.map(opt => opt.value);
  61.         return rows.filter(element => authors.indexOf(element.author) !== -1);
  62.       }
  63.     },{
  64.       Header: 'Title',
  65.       accessor: 'title',
  66.       filterable: false
  67.     }
  68.   ];
  69.  
  70.   return (
  71.     <section>
  72.       <ReactTable
  73.         columns={columns}
  74.         data={data}
  75.         filterable
  76.       />
  77.     </section>
  78.   );
  79. }
  80.  
  81. export default App;
Advertisement
Add Comment
Please, Sign In to add comment