How To Create Search Filter In React Native?

Hello guys, In this example, we will see how you can create Search Filter For List in React Native app. It is very easy so let's start with it without wasting any time.




So first of all we need to create a fresh project using cli.
npx react-native init searchFilter
Go to the project directory.
cd searchFilter
After this, try to run that blank project on both iOS and android devices.
npx react-native run-ios  (mac only)
npx react-native run-android
If everything ok, you will see blank React Native app as shown in image.

Now, install NativeBase library for UI purposes.
yarn add native-base
Link the project assets. 
npx react-native link
So after that you need to replace App.js with this code.
import React, {Component} from 'react';
import {
  Container,
  Header,
  Content,
  Left,
  Body,
  Icon,
  Text,
  ListItem,
  Thumbnail,
  Item,
  Input,
} from 'native-base';
let helperArray = require('./userList.json');
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allUsers: helperArray,
      usersFiltered: helperArray,
    };
  }
  componentDidMount() {}
  searchUser = text => {
    this.setState({
      usersFiltered: this.state.allUsers.filter(i =>
        i.name.toLowerCase().includes(text.toLowerCase()),
      ),
    });
  };
  render() {
    return (
      <Container>
        <Header searchBar rounded>
          <Item>
            <Icon name="ios-search" />
            <Input
              placeholder="Search"
              onChangeText={text => this.searchUser(text)}
            />
          </Item>
        </Header>
        <Content>
          {this.state.usersFiltered.map(item => (
            <ListItem avatar>
              <Left>
                <Thumbnail source={{uri: item.image}} />
              </Left>
              <Body>
                <Text>{item.name}</Text>
                <Text note>{item.address}</Text>
              </Body>
            </ListItem>
          ))}
        </Content>
      </Container>
    );
  }
}
In above code you can see we import a userList.json file; that's why because we need user name, address & images for our app. It is for testing purposes. Here is the sample view of that json file.
Save everything and run the project again by using following commands.
npx react-native run-ios  (mac only)
npx react-native run-android
You will see your List Search Filter App is ready and showing in the simulators (or devices). Output images are attached and link to the video of the project's coding as given below.


I hope you like the article regarding Search Filter. This is how you can create it in the React Native app for Android and iOS. If you have any questions or you want to get a tutorial on some topic, you can comment below.
There will be more posts coming soon. Stay tuned! Bye. 🙂

Post a Comment

0 Comments