Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchBar in FlatList loses focus after typing

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]}
    />
  )
}
like image 585
bdoubleu Avatar asked Mar 10 '20 17:03

bdoubleu


1 Answers

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}
        />
      }
    />
like image 150
Brian Avatar answered Oct 03 '22 06:10

Brian