clauderic / react-tiny-virtual-list

A tiny but mighty 3kb list virtualization library, with zero dependencies 💪 Supports variable heights/widths, sticky items, scrolling to index, and more!
https://clauderic.github.io/react-tiny-virtual-list/
MIT License
2.47k stars 164 forks source link

Support for Live Filter Search? #10

Closed marcellodesales closed 7 years ago

marcellodesales commented 7 years ago

Instead of Jump to Index... Is there a way to use live as the user types the character?

clauderic commented 7 years ago

Sure, you can do this by dynamically filtering your data and updating the number of rows accordingly.

Here's a simplified example using a list of countries, but you'll likely want to use a more sophisticated search algorithm though, you can look at the Levenshtein distance algorithm, or something like match-sorter if you need more flexibility.

import React, {Component} from 'react';
import VirtualList from 'react-tiny-virtual-list';

const countries = [
  'Switzerland',
  'Canada',
  'United Kingdom',
  'Germany',
  'Japan',
  'Sweden',
  'United States',
  'Australia',
  'France',
  'Norway',
];

class MyComponent extends Component {
  state = {
    inputValue: '',
    data: countries,
  };
  handleChange = (value) => {
    const {inputValue} = this.state;

    this.setState({
      data: countries.filter((country) =>
        country.indexOf(inputValue) !== -1
      ),
    });
  }
  render() {
    const {inputValue, data} = this.state;

    return (
      <div>
        <input onChange={this.handleChange} value={inputValue} />
        <VirtualList
          width='100%'
          height={600}
          itemCount={data.length}
          itemSize={50}
          renderItem={({index, style}) =>
            <div key={index} style={style}>
              {data[index]}
            </div>
          }
        />
      </div>
    );
  }
}
marcellodesales commented 7 years ago

@clauderic u rock! Thank you!