React Native — SearchBar in FlatList loses focus after typing

Aryan Mittal
2 min readJun 23, 2021

While building the React Native app for Voluntime, I was displaying a list of events and wanted to add a search bar to the header. So, I experimented with FlatList and the ListHeaderComponent prop.

According to the React Native docs, the ListHeaderComponent is “rendered at the top of all the items”. So, it felt like the perfect solution for my search bar.

The problem I encountered is that after typing one character the search bar loses focus and the keyboard disappears — it’s almost like the component re-renders. What’s happening?

Here’s what my code looked like:

The key here is that my Searchbar component was rendered inside an arrow function when it was passed to the ListHeaderComponent prop. Every time the search value changed, the FlatList re-rendered and a new arrow function was created on every render. This caused the search bar to be replaced with a new one, losing its focused state and removing the keyboard.

This happens due to the way arrow functions work in React props. Every time the render code is run, a new arrow function gets created that returns a new Searchbar component, and React doesn’t persist the old component.

To solve the problem, simply move the Searchbar component out of the arrow function. Instead, you can pass the component directly, like shown:

This does not create a new Searchbar component on every render, which fixes the keyboard problem and is also more performant. Hopefully this article helped you and taught you something new about how React works!

--

--

Aryan Mittal

High school student with a passion for coding and helping others with my knowledge.