Home > Back-end >  how to search item in listed element react native
how to search item in listed element react native

Time:10-04

am stuck with a problem, when am trying to search element from listed data its not working , I seem lots of document ad I applied it, but still its work for me, can anyone help me. if you have any question please free feel to ask any time.

home.js

This is Home.js file where I wrote my all code. and here I use some React native paper components.

import React, { useEffect, useState } from 'react'
import { Text, View, FlatList, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
import { Avatar } from 'react-native-elements';
import { Searchbar, Provider, Portal, TextInput, Button } from 'react-native-paper';
import { AntDesign, Entypo } from '@expo/vector-icons';
import Modal from "react-native-modal";

export default function Home() {

  const [searchquery, setSearchquery] = React.useState();
  const [isModalVisible, setModalVisible] = useState(false);
  const [name, setName] = React.useState('');
  const [number, setNumber] = React.useState('');


  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  const filterItem = (text) => {
    if (text) {
      const newData = users.filter((item) => {
        const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
        const textData = text.toUpperCase();
        return itemData.indexOf(textData) > -1
      })
      setUser(newData);
      setSearchquery(text)
    }
    else{
      setUser(users)
      setSearchquery(text);
    }
  }

  const [users, setUser] = useState([
    {
      id: 1,
      name: "Ashish Nirvikar",
      number: 3289768909,
    },
    {
      id: 2,
      name: "Drew Macntyre",
      number: 3345661276
    },
    {
      id: 3,
      name: "Jonh Cena",
      number: 9087392878
    },
    {
      id: 4,
      name: "Rock Samoa",
      number: 9723780928
    },
    {
      id: 5,
      name: "Boby Lashely",
      number: 8769213678
    },
    {
      id: 6,
      name: "Seth Rollins",
      number: 6890326741
    },
  ])

  return (
    <View >
      <Searchbar
        placeholder="Search Contacts"
        onChangeText={(text) => filterItem(text)}
        onClear={(users) => setUser('')}
        value={searchquery}
        style={{ marginTop: 30, marginHorizontal: 10 }}
      />
      <ScrollView>
        {
          users.map((item, index) => {
            return (
              <View key={index} style={styles.names}>
                <Text style={{ color: 'black', fontSize: 20, fontWeight: 'bold' }}>Name : {item.name}</Text>
                <Text style={{ color: 'black' }}>Mobile no : {item.number}</Text>
              </View>
            )
          })
        }
      </ScrollView>
      <Modal isVisible={isModalVisible} style={{ backgroundColor: 'white', height: 50, marginBottom: 200, marginTop: 100 }}>
        <View style={{ flex: 2 }}>
          <Text style={{ color: 'black', fontSize: 50, textAlign: 'center' }}>Add Contact</Text>
          <TextInput
            style={styles.input}
            label="Enter Full name"
            value={name}
            onChangeText={text => setName(text)}
          />
          <TextInput
            style={styles.input1}
            label="Enter Mobile Number"
            value={number}
            onChangeText={text => setNumber(text)}
          />
          <Button title="Hide modal" onPress={toggleModal} style={{ color: 'black', backgroundColor: 'white', borderWidth: 1, borderColor: 'gray', marginHorizontal: 10, marginTop: 15 }}>Cancle</Button>
        </View>
      </Modal>

      <AntDesign name="plus" size={34} color="black" style={styles.plus} onPress={toggleModal} />
    </View>
  );
}


const styles = StyleSheet.create({
  customText: {
    padding: 10,
    marginTop: 20,
    textAlign: 'center',
    backgroundColor: 'lightgray',
    fontWeight: 'bold',
    fontSize: 20
  },
  plus: {
    fontSize: 50,
    position: 'absolute',
    top: 680,
    right: 40,
    backgroundColor: 'pink',
    borderRadius: 15,
    borderWidth: 0.5,
    padding: 5,
  },
  names: {
    padding: 15,
    fontSize: 25,
    fontWeight: 'bold',
    backgroundColor: 'lightgray',
    marginTop: 10,
    borderRadius: 20,
    color: 'black'
  },
  addcontactname: {
    fontSize: 30,
    textAlign: 'center',
    marginTop: 10,
    marginBottom: 30
  },
  input: {
    marginHorizontal: 10,
    marginBottom: 20,
    marginTop: 20
  },
  input1: {
    marginHorizontal: 10,
    marginBottom: 10,
  }
});

CodePudding user response:

Your Searchbar should be a controlled input (call setSearchquery with the change value from the Searchbar).

Then you can use the value of searchquery to perform the filtering inline in your jsx.

Finally, use FlatList to render a list of items instead of a map inside a ScrollView.

In your example, there's no need for the list of users to be stored in state.

import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet, ScrollView, FlatList } from 'react-native';
import { Searchbar } from 'react-native-paper';

const data = [...];

export default function Home() {
  const [searchquery, setSearchquery] = React.useState();
  const [name, setName] = React.useState('');

  return (
    <FlatList
      data={data}
      ListHeaderComponent={() => (
        <Searchbar
          placeholder="Search Contacts"
          onChangeText={(text) => setSearchquery(text)}
          value={searchquery}
          style={{ marginTop: 30, marginHorizontal: 10 }}
        />
      )}
      renderItem={({ item, index }) => (
        <View key={index} style={styles.names}>
          <Text style={{ color: 'black', fontSize: 20, fontWeight: 'bold' }}>
            Name : {item.name}
          </Text>
          <Text style={{ color: 'black' }}>Mobile no : {item.number}</Text>
        </View>
      )}
    />
  );
}

Snack

CodePudding user response:

Try this

 const filterItem = (text) => {
      users.filter((item) => {
        return item.name.toLowerCase().inludes(text.toLowerCase())
      })
      setSearchquery(text)
  }


   <ScrollView>
     {
          filterItem(users).map((item, index) => {
            return (
              <View key={index} style={styles.names}>
                <Text style={{ color: 'black', fontSize: 20, fontWeight: 'bold' }}>Name : {item.name}</Text>
                <Text style={{ color: 'black' }}>Mobile no : {item.number}</Text>
              </View>
            )
          })
        }
     </ScrollView>

CodePudding user response:

you can try with this code if it will not work then call filterItem function with bracket and parameter also my code is working while name is lowercase...

<Searchbar

    placeholder="Search Contacts"

    onChangeText={filterItem}

    onClear={(users) => setUser('')}

    value={searchquery}

    style={{ marginTop: 30, marginHorizontal: 10 }}

  />

const filterItem = (text) => {

setSearchquery(text)
let searchText = text.toLowerCase()
let filterData = users
filterData = filterData.filter(function (id) {
  return id.name.toLowerCase().includes(searchText)
})
setUser(filterData);
if (text === "") {
 setUser(users);
}

}

  • Related