React Native Search Bar

Learn via video courses
Topics Covered

Overview

Search functionality is a crucial aspect of many mobile applications, allowing users to easily find and access relevant content. In this article, we will explore how to build a search bar in React Native from scratch. We'll cover the necessary steps, and code implementation, and demonstrate its functionality in a sample project.

Introduction

Imagine the digital environment of today without any means of data filtration. Unimaginable, yes? One way to use such a filter is in a search bar. Many instances of search bars should come to mind if you think about any app on your smartphone right now.

The search bar component provides users with a convenient way to search for specific items within a given context. By implementing a search bar in React Native, we can enhance the user experience and make content discovery more efficient.

Prerequisites

Before diving into building a React Native search bar, ensure that you have the following prerequisites:

  • Basic understanding of React Native.
  • Familiarity with JavaScript and ES6 syntax.
  • React Native development environment set up

Building a React Native Search Bar from Scratch

Let's start by delving into the code itself! Go to the folder where your project will be stored first. Run "expo init my-project" inside of this directory to start the Expo project. You can use any other name for "my project."

After that, use cd my-project to get to the freshly created directory and type expo start to launch the development server. You may pick the type of device you wish to use with Expo; in the demonstration and the video above, I used an iPhone 12.

cd into the directory where to store your project:

initialize the expo project:

navigate inside the newly created project:

run the development server:

I always add a screens directory and a components directory to my React Native applications to keep things organized. Because we only need to examine one screen while the search bar is in use, each screen folder will only contain a single file in this case.

Any React Native components can be outsourced to a different file and will be stored in the components folder. List.js and SearchBar.js are two scripts that will be present in this sample project.

First, let's examine the SearchBar.js file.

Defining Our Search Bar in SearchBar.js

The contents of our SearchBar.js file are listed below. This component is simply in charge of showing the search bar itself; it does not currently have any filtering logic.

Lines 2-4 show that we don't need to import a lot to build a custom search bar. The @expo/vector-icons imports, which we'll utilize to construct some attractive icons, are the most intriguing in this list.

Line 9 is where we define the search bar itself. You'll see that I utilized conditional style to distinguish between two "versions" of the search bar in the lines following (67-83): an unclicked search bar and a clicked search bar.

This will be clearer if you examine the following bit of code:

The styles.searchBar clicked will be used if clicked is set to true. If not, styles.searchBar unclicked will be used instead.

defining-our-search-bar-in-searchbar-js

Clicked is used to determine whether the bar was clicked. When we examine the home page, which is where all the props are controlled, later in the course, we'll reach this point.

We can also discover the search icon (lines 17–22), the text input (lines 24-32), and the cross icon (lines 35–38) inside of the View>, which houses the search bar. In the part that follows, let's go through these.

Implementing Text Input Listeners in React Native

There are some intriguing textual elements here. Take the onChangeText property as our first example.

This function allows you to include a listener that will be activated any time the content in the TextInput field changes. In this instance, the setSearchPhrase function is used. The text entered by our child component, SearchBar.js, may then be sent to its parent, Home.js.

The searchPhrase component then passes this text input to the TextInput component's value property. As implied by the name, this attribute specifies the actual value that will be shown for the text input.

To instruct the app what to do when the search bar is clicked, we specify the onFocus property in the last step. Only when clicked is set to true are the cancel button (line 41) and the cross (line 34) presented.

If you're wondering why we even need to give this data to the parent component, remember that we will require the search term and other information not only in the SearchBar.js component, where we'll filter the data but also in the List.js component.

Filtering the Text Input in List.js

I'm utilizing a FlatList component from React Native to render the data. You'll see that in our situation, FlatList accepts data, renderItem, and keyExtractor as attributes if you look at lines 41–45 of List.js.

The Item, which will show the name and specifics of the programming language, is the first item we need to specify inline 11. Line 20 of the subsequent step, which defines what occurs with this Item, begins. In that section, the list of programming languages is filtered based on the text supplied.

We specify how the item we just specified should be presented in the FlatList component in the renderItem method. In this instance, we distinguish between three scenarios. Line 22 of the first one refers to the scenario where no input is provided ((searchPhrase === "")). Here, we just render the list's whole inventory of items.

Use the (item.name.toUpperCase().includes(searchPhrase.toUpperCase().trim(). In line 26, we filter the names of the programming languages using replace(/s/g, ""). We eliminate all white space and change the input and names to uppercase.

The actual filters are represented by the three tests that are given in the renderItem function. We check whether the text input (searchPhrase) is present in the item's name (the programming language) at line 27 of List.js. Every item in our database will undergo this check, and if it is successful, the item will be rendered.

In line 30, we do the same, only we apply it to the descriptions of the programming languages.

Please feel free to experiment on your own as there are many different methods to apply the filtering logic.

Now that everything has been set up for FlatList, let's look at what this List component returns (lines 35–50). You can see that I wrapped the FlatList with a View on line 37. This is because I wanted to include a feature that makes sure the keyboard closes and clicks are set to false if we tap or click outside of the search bar. This logic is carried out by onStartShouldSetResponder=() => setClicked(false).

The parent component of FlatList's data property (line 43) will supply the data. Our const renderItem from line 20 will be the renderItem that is set. We'll use the id of the relevant item for the keyExtractor.

A unique key for an object is extracted by the keyExtractor. This is crucial for caching and effectively rearranging the FlatList's entries.

I'll go through the Home.js component, which is where it all comes together, in the following step. Hold on, you're nearly there!

Finalizing Our React Native Search Bar in the Home.js File

Home.js file:

In lines 9 and 10, we import our own components List and SearchBar first. We specify three distinct states after that, and you should be familiar with clicked and searchPhrase. The useEffect Hook in line 18 will make use of the third one, fakeData.

I made up the scenario where we collected information from an API endpoint to make this example as plausible as possible. We build an asynchronous method named getData within the useEffect Hook, where it retrieves data from the fictitious API and stores it in a variable called fakeData. In line 26, we call the function right away after it has been defined. To ensure that this Hook is only used once the component has been displayed, I did not declare any dependents on line 27.

The implementation of the header "Programming Languages" uses the expressions "!clicked && Programming Languages,", and based on the value of clicked, the header will be shown differently. This implies that if the searchBar is not clicked, the word "Programming Languages" will not be displayed.

Then, using the properties searchPhrase, setSearchPhrase, clicked, and setClicked, we render our SearchBar component.

We need something to render during the many seconds it may take to fetch the data. In this instance, let's render a loading spinner. We will thus render the loading spinner with!fakeData? () as long as fakeData is undefined, and if fakeData is specified, the List component will be presented.

And that's basically it! Ultimately, all you have to do is import this Home.js file into your App.js file as follows:

Conclusion

  • Building a search bar in React Native allows for enhanced user experience and efficient content discovery.
  • The process involves creating a project directory, defining the search bar component, implementing text input listeners, filtering the input, and finalizing the search bar in the main component.
  • By following these steps, developers can integrate a fully functional search bar into their React Native applications.