Reputation: 6107
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]}
/>
)
}
Upvotes: 9
Views: 2201
Reputation: 1324
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}
/>
}
/>
Upvotes: 15
Reputation: 812
The keyboard is disappearing because the component is re-rendering again and because it is a functional component, the <SearchBar/>
is re-rendering again. To solve this problem change your component to a class-based component or try separating the <SearchBar/>
from this component to the parent component.
Upvotes: 0