showing results for - "how to make sugesstion input feild in react"
Alberto
31 Jan 2017
1const INPUT_TIMEOUT = 250; //ms - It's our input delay
2class TodoApp extends React.Component {
3    constructor(props) {
4      super(props);
5      this.state = {
6        value: '',
7        predictions: [],
8      };
9
10      this.onChange = this.onChange.bind(this);
11    }
12
13    getPredictions(value) {
14      // let's say that it's an API call
15      return [
16        'Boston',
17        'Los Angeles',
18        'San Diego',
19        'San Franciso',
20        'Sacramento',
21        'New York',
22        'New Jersie',
23        'Chicago',
24      ].filter(item => item.toLowerCase().indexOf(value.toLowerCase()) !== -1);
25    }
26
27    onChange(e) {
28      // clear timeout when input changes value
29      clearTimeout(this.timeout);
30      const value = e.target.value;
31      this.setState({
32        value
33      });
34
35      if (value.length > 0) {
36        // make delayed api call
37        this.timeout = setTimeout(() => {
38          const predictions = this.getPredictions(value);
39          this.setState({
40            predictions
41          });
42        }, INPUT_TIMEOUT);
43      } else {
44        this.setState({
45          predictions: []
46        });
47      }
48    }
49
50    render() {
51        return ( 
52          <div >
53          <input type = "text" value={this.state.value} onChange = {this.onChange}/>
54            <div> 
55            {
56              this.state.predictions.map((item, index) => (
57                <div key={index + item}>{item}</div>
58              ))
59            } 
60            </div> 
61          </div>
62        )
63    }
64}
65
66ReactDOM.render( <TodoApp />, document.querySelector("#app"))
67