lolix
lolix

Reputation: 1537

Create a search bar in a listview

I am creating a Search bar in a list view with a list of multiples types of food, this search bar can filter the results.

When I search a specific food and select this food, If I erase the search bar another food is selected.

You can see the problem in this gif: https://giphy.com/gifs/3oKIPpagpRTfnuA9vW

How can I solve this problem?

Code:

class ListFood extends Component {

  constructor() {
      super();
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.state = {
        ds: ds,
        dataSource: ds.cloneWithRows(dataDemo),
        rawData: dataDemo,
      };
    }

    setSearchText(event) {
     let searchText = event.nativeEvent.text;
     this.setState({searchText});
     data = dataDemo

     let filteredData = this.filterNotes(searchText, data);
     ds = this.state.ds;

     this.setState({
       dataSource: ds.cloneWithRows(filteredData),
       rawData: data,
     });

    }

    filterNotes(searchText, notes) {
      let text = searchText.toLowerCase();

      return notes.filter((n) => {
        let note = n.toLowerCase();
        return note.search(text) !== -1;
      });
    }

    render() {
      return (
        <View>
          <TextInput
            value={this.state.searchText}
            onChange={this.setSearchText.bind(this)}
          />
          <ListView
            dataSource={this.state.dataSource}
            renderRow={(data) => <Row state={this.state.CheckBoxState} data={data} />}
          />
        </View>

      );
    }
}

row:

class Row extends Component {
  constructor(props) {
    super(props);
    this.state = { checked: false };
  }

  render() {
    return (
      <View´>
        <CheckBox
          onPress={() => this.setState({
            checked: !this.state.checked
          })}
          checked={this.state.checked}
        />
        <Text>
          { this.props.data }
        </Text>
      </View>
    );
  }
}

Upvotes: 0

Views: 1639

Answers (1)

coder hacker
coder hacker

Reputation: 4868

I have had same problem before where the row change is not correctly detected. I did a workaround by initializing the datasource every time I had new data.

So try something like

setSearchText(event) {
     let searchText = event.nativeEvent.text;
     this.setState({searchText});
     data = dataDemo

     let filteredData = this.filterNotes(searchText, data);
     const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

     this.setState({
       dataSource: ds.cloneWithRows(filteredData),
       rawData: data,
     });

    }

Upvotes: 2

Related Questions