最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - input search filter array using hooks - Stack Overflow

programmeradmin6浏览0评论

I want to filter over an array using react hooks. It should be a fairly straight forward task, but I am assuming it is something to do with hooks being updated asynchronously, although this could be wrong.

I am fairly stumped, but have included a code sandbox and my code below:

const teams_data = [
  "tottenham",
  "arsenal",
  "man utd",
  "liverpool",
  "chelsea",
  "west ham"
];

function App() {
  const [teams, setTeams] = React.useState(teams_data);
  const [search, setSearch] = React.useState("");

  return (
    <div className="App">
      <input
        onChange={e => {
          const test = teams.filter(team => {
            return team.toLowerCase().includes(e.target.value.toLowerCase());
          });
          console.log("test: ", test);

          // unment line below and teams is logged as I want
          setTeams(test);
          setSearch(e.target.value);
        }}
        type="text"
        value={search}
      />
      {teams.map(team => (
        <p>{team}</p>
      ))}
    </div>
  );
}

I want to filter over an array using react hooks. It should be a fairly straight forward task, but I am assuming it is something to do with hooks being updated asynchronously, although this could be wrong.

I am fairly stumped, but have included a code sandbox and my code below:

const teams_data = [
  "tottenham",
  "arsenal",
  "man utd",
  "liverpool",
  "chelsea",
  "west ham"
];

function App() {
  const [teams, setTeams] = React.useState(teams_data);
  const [search, setSearch] = React.useState("");

  return (
    <div className="App">
      <input
        onChange={e => {
          const test = teams.filter(team => {
            return team.toLowerCase().includes(e.target.value.toLowerCase());
          });
          console.log("test: ", test);

          // unment line below and teams is logged as I want
          setTeams(test);
          setSearch(e.target.value);
        }}
        type="text"
        value={search}
      />
      {teams.map(team => (
        <p>{team}</p>
      ))}
    </div>
  );
}
Share Improve this question asked Aug 29, 2019 at 14:46 peter flanaganpeter flanagan 9,85027 gold badges82 silver badges140 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You need to filter the original data :

  const test = teams_data.filter(team => {
    return team.toLowerCase().includes(e.target.value.toLowerCase());
  });

https://codesandbox.io/s/thirsty-austin-uqx8k

You just need to add another state for search results

    const [data , setData] = useState(teams);
    const [query, setQuery] = useState('')
    const[res , setRes] = useState([]);
    return (
      <div className="App container">
          <form onSubmit = {(e) => e.preventDefault()}>
              <input type = "search" className = "srh" placeholder = "search about..." 
              onChange = {(e) => {
                const test = data.filter(team => {
                  return (
                    team.toLowerCase().includes(e.target.value.toLowerCase())
                  )
                })
                setRes(test)
                if(e.target.value === '') setRes([])
              }}
              />
          </form>
          <div>
          {
            res.map((item , i) => (
            <p key = {i}>{item}</p>
            ))
          }
          </div>
      </div>
    );

I've made custom hook.

It receives the array as a first param
the search variable as a second
and the property you want to filter by

I hope it's helpfull

export function useSearch(array: any[], search: string, field: string) {
  const filteredArray = array.filter((entry) => {
    if (search === "") return entry;
    else if (
      entry[field].toLocaleLowerCase().includes(search.toLocaleLowerCase())
    )
      return entry;
  });
  return {
    filteredArray
  };
}

Them apply the filtered array to your map function

import { useSearch } from "./useSearch";
import { useState } from "react";

const array = [
  {
    id: 1,
    name: "Humberto Guenzo Yoshimoto"
  },
  {
    id: 2,
    name: "Diego Braga"
  },
  {
    id: 3,
    name: "Hudson Teixeira"
  },
  {
    id: 4,
    name: "Matheus Doimo"
  }
];

type FilteredArrayTypes = {
  id: number;
  name: string;
};

export default function App() {
  const [searchByFullName, setSearchByFullName] = useState("");

  const { filteredArray } = useSearch(array, searchByFullName, "name");

  return (
    <div className="App">
      <h1>Search list</h1>
      <input
        onChange={(e) => setSearchByFullName(e.target.value)}
        type="text"
        value={searchByFullName}
        placeholder="search"
      />
      {filteredArray.map((entry: FilteredArrayTypes) => {
        return (
          <ul>
            <li>{entry.name}</li>
          </ul>
        );
      })}
    </div>
  );
}

Here goes a sandbox with the code: here

发布评论

评论列表(0)

  1. 暂无评论