How can I search in react by taking in multiple object values?

Viewed 36

Pls see below my code,trying to search by comparing the input value with multiple object values.

<input type="search" placeholder="Search by Topic, Level or Subject..."
  onChange={(e) => {
    const searchGames = search.filter(item => item.Topic.toLowerCase().includes(e.target.value.toLowerCase()) ? item : null);
    setGame(searchGames);
    const searchGames2 = search.filter(item => item.Level.toLowerCase().includes(e.target.value.toLowerCase()) ? item : null);
    setGame(searchGames2);
    const searchGames3 = search.filter(item => item.Subject.toLowerCase().includes(e.target.value.toLowerCase()) ? item : null);
    setGame(searchGames3);
  }}
/>
1 Answers

Seems like a more of programming question than react one.

As you may have noticed your example code lacked "or".

Try just checking if any of the conditions are true.

<input type="search" placeholder="Search by Topic, Level or Subject..."
  onChange={(e) => {
    const filteredGames = search.filter(item => {
      const topicIncludes = item.Topic.toLowerCase().includes(e.target.value.toLowerCase());
      const levelIncludes = item.Level.toLowerCase().includes(e.target.value.toLowerCase());
      const subjectIncludes = item.Subject.toLowerCase().includes(e.target.value.toLowerCase());
      return topicIncludes || levelIncludes || subjectIncludes;
    })
    setGame(filteredGames)
  }}
/>

Also, setting a state multiple times in a row is almost never a good idea.

Related