Home > Net >  I want to display nothing when Search input is empty
I want to display nothing when Search input is empty

Time:04-02

I am actually using a search function to search in a list (data), the thing is it's showing all the information in the list by default. How can I hide all the list ? And show it (the results) only once the user typed something in the search input.

Thanks in advance,

Code that I am using :

 const [search, setNewSearch] = useState("");

    const handleSearchChange = (e) => {
    setNewSearch(e.target.value);
    };

    const filtered = !search
        ? data
        : data.filter((item) =>
            item.titre.toLowerCase().includes(search.toLowerCase())
        
        );

return view :

 <TextInput style={styles.search}
                    value={search} 
                    onChange={handleSearchChange}
                    ></TextInput>
                    <Text style={styles.text}>Résultat rapide :</Text>
                    <View style={styles.text}>
                    {filtered.map((item) => {
                    return (
                        <p key={item.id}>
                            Nom: {item.titre} 
                           - Date: {item.date} 
                           - Rating: {item.note}/10
                        </p>
                    );
                      })}
                    </View>

image of the app : see image

CodePudding user response:

You are using !search which returns true if search is undefined. However, your default state is set to the empty string "", which is not undefined, thus !"" returns true.

Thus, data is always returned. You need to check the length of the search string and if it is equal to zero, return the filtered data.

const filtered = search.length > 0
        ? data.filter((item) =>
            item.titre.toLowerCase().includes(search.toLowerCase())
         ) : data

CodePudding user response:

Pass null to filtered if search is empty.

const filtered = search.length === 0
    ? null
    : data.filter((item) =>
        item.titre.toLowerCase().includes(search.toLowerCase())
    );

and on your view, return fragment when filtered is null

 <TextInput style={styles.search}
                    value={search} 
                    onChange={handleSearchChange}
                    ></TextInput>
                    <Text style={styles.text}>Résultat rapide :</Text>
                    <View style={styles.text}>
                    {!filtered ? <></> : filtered.map((item) => {
                    return (
                        <p key={item.id}>
                            Nom: {item.titre} 
                           - Date: {item.date} 
                           - Rating: {item.note}/10
                        </p>
                    );
                      })}
                    </View>
  • Related