I'm using a SearchBar component in a FlastList through the ListHeaderComponent prop and filtering the list of items based on the search value. The problem is that after typing one character the search bar loses focus (keyboard is removed) - it's almost like the component re-renders? What am I missing here?
I'm using Android and the problem does not occur if I move the SearchBar outside of the FlatList.
import React from 'react'
import {FlatList, View} from 'react-native'
import { ListItem, SearchBar } from 'react-native-elements'
export const Component = (props) => {
  const [search, setSearch] = React.useState('');
  const [items, setItems] = React.useState([
    { id: 1, name: 'One Thousand' },
    { id: 2, name: 'Two Hundred' },
  ]);
  const filterItems = (items, filter) => {
    return items.filter(item => item.name.toLowerCase().includes(filter.toLowerCase()))
  }
  const renderHeader = () => (
    <SearchBar
      placeholder='Search...'
      onChangeText={setSearch}
      value={search}
    />
  );
  const renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      bottomDivider
      chevron
    />
  );
  return (
    <FlatList
      data={filterItems(items, search)}
      keyExtractor={item => item.id.toString()}
      renderItem={renderItem}
      ListHeaderComponent={renderHeader}
      stickyHeaderIndices={[0]}
    />
  )
}
To solve this problem easily, just try not to render the ListHeaderComponent using a separate component, instead use render directly
   <FlatList
      ...
      ListHeaderComponent={
        <Searchbar
          placeholder="Search"
          onChangeText={query => {
            setSearch(query);
          }}
          value={search}
        />
      }
    />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With