Open In App

How to add SearchBar in React Native ?

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article we’ll add search functionality in React-Native. This can be regarded as a continuation to React native flatlist component/. In the aforementioned article we created a flatlist using Flatlist component, let’s make it searchable using SearchBar component. To add a SearchBar to your flatlist, the basic syntax looks like following:

Basic Syntax:

<SearchBar
    placeholder="Type Here..."
    onChangeText={this.updateSearch}
    value={search}
/>

Approach: The above syntax adds a standard platform-specific search bar in your application, which is usually a rectangular box with space for input. Upon scrolling to the implementation section you’d notice that we add a prop placeholder that specifies the default value that the search bar displays when opened. Also, we want the search bar to be light-themed with rounded edges, hence the following props. Now when we want to search a value we’d want to display that value being entered in the search bar, for that we add a object search value from Search class, by default it is empty but as and when we type it is modified and stores our present text input. Since the search values are custom we turn off the auto Correct option and invoke the search Function as soon as the text is entered in the search field.

Props in SearchBar:

  • cancelButtonProps: It specifies various props passed to cancel Button, these can customize its color, button style , text color etc.
  • cancelButtonTitle: It used to customize title of the cancel button present on the right side.
  • cancelIcon:  This prop allows to override the Icon props or use a custom component, also this is specific to Android platform.
  • clearIcon: This prop allows to override the Icon props or use a custom component. Values such as null or false can be used to hide the icon.
  • containerStyle: The container of the SearchBar can be stylised using this prop.
  • inputContainerStyle: this prop is used to style the container where the text is input.
  • inputStyle: This prop is used to stylize the input text.
  • leftIconContainerStyle: style the icon container on the left side.
  • lightTheme : This prop changes the theme to light theme.
  • loadingProps: This prop is passed to ActivityIndicator.
  • onCancel:  This prop lets callback fired when pressing the cancel button (iOS) or the back icon (Android).
  • onChangeText: This prop invokes the method that should fire when text is changed.
  • onClear:  This specifies the method to fire when input is cleared.
  • placeholder: This prop is used to set the placeholder text.
  • placeholderTextColor: This prop sets the color of the placeholder text.
  • platform:  This prop specifies the look and feel of the search bar. The values to choose from are “default”, “ios”, “android”.
  • rightIconContainerStyle: We can style the icon container on the right side using this prop.
  • round : This prop is used to change the TextInput styling to rounded corners.
  • searchIcon: This prop allows to override the Icon props or use a custom component. Use null or false to hide the icon.
  • showCancel : This prop if set to true the cancel button will stay visible even after blur events.
  • showLoading: This prop shows the loading ActivityIndicator effect.
  • underlineColorAndroid: This prop specifies transparent underline color, other than the default one.

Implementation:

  • Step 1: Open your terminal and install expo-cli , if not installed already.
npm install --global expo-cli
  • Step 2: After installing let’s initialise a project , if not done already.
expo init dummy
  • Step 3: Now navigate to your project.
cd dummy

Folder structure: If you followed the steps above, your folder structure should look something like this.

Example: Now let’s see the implementation of how to add a search bar using the above approach.

Filename: App.js

javascript




import React, { Component } from "react";
import { StyleSheet, Text, View, FlatList } from "react-native";
import { ListItem, SearchBar } from "react-native-elements";
import filter from "lodash.filter";
  
const DATA = [
  {
    id: "1",
    title: "Data Structures",
  },
  {
    id: "2",
    title: "STL",
  },
  {
    id: "3",
    title: "C++",
  },
  {
    id: "4",
    title: "Java",
  },
  {
    id: "5",
    title: "Python",
  },
  {
    id: "6",
    title: "CP",
  },
  {
    id: "7",
    title: "ReactJs",
  },
  {
    id: "8",
    title: "NodeJs",
  },
  {
    id: "9",
    title: "MongoDb",
  },
  {
    id: "10",
    title: "ExpressJs",
  },
  {
    id: "11",
    title: "PHP",
  },
  {
    id: "12",
    title: "MySql",
  },
];
  
const Item = ({ title }) => {
  return (
    <View style={styles.item}>
      <Text>{title}</Text>
    </View>
  );
};
  
const renderItem = ({ item }) => <Item title={item.title} />;
class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: DATA,
      error: null,
      searchValue: "",
    };
    this.arrayholder = DATA;
  }
  
  searchFunction = (text) => {
    const updatedData = this.arrayholder.filter((item) => {
      const item_data = `${item.title.toUpperCase()})`;
      const text_data = text.toUpperCase();
      return item_data.indexOf(text_data) > -1;
    });
    this.setState({ data: updatedData, searchValue: text });
  };
  
  render() {
    return (
      <View style={styles.container}>
        <SearchBar
          placeholder="Search Here..."
          lightTheme
          round
          value={this.state.searchValue}
          onChangeText={(text) => this.searchFunction(text)}
          autoCorrect={false}
        />
        <FlatList
          data={this.state.data}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
        />
      </View>
    );
  }
}
  
export default Search;
  
const styles = StyleSheet.create({
  container: {
    marginTop: 30,
    padding: 2,
  },
  item: {
    backgroundColor: "#f5f520",
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
});


Run the application: Now, start your server by running the following command

npm run web

You can scan your generated QR Code from Expo Go app and get this output.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads