Friday, 2 April 2021

ReactJS realtime search filter of array of arrays

I'm trying to create a realtime filtering search for a long list of items, items are in the form of an array containing arrays with a string and a object, as:

const items = [
      ["cats", [
        {name: "name", img: "img/img.jpg"},
        {name: "name2", img: "img2/img.jpg"},
        ...
      ]],
      ["dogs", [
        {name: "name", img: "img/img.jpg"},
        {name: "name2", img: "img2/img.jpg"},
        ...
      ]],
      ...
]

and I'm trying to filter it by name values.

What I tried is:

export default function Page({ items }) {
const [searchTerm, setSearchTerm] = React.useState("");
const [searchResults, setSearchResults] = React.useState(items);
const handleChange = event => {
    setSearchTerm(event.target.value);
}

useEffect(() => {
    var f=0, results = []
    while (f < items.length){
        if(items[f][1].includes(searchTerm)){
            results.push(result)
        }
        f++
    }
    
    setSearchResults(results);
}, [searchTerm]);

return (
        <div>
            <input
                type="text"
                placeholder="Search"
                value={searchTerm}
                onChange={handleChange}
            />
            {searchResults.map((cl, index) => (
                <div key={index}>
                  <h2>{cl[0]}</h2>
                  <ScrollContainer> 
                    {cl[1].map((item, i) => (
                      <h3>{item.name}</h1>
                    ))}
                  </ScrollContainer>
                </div>
             ))}

but it throws error:

ChunkLoadError: Loading chunk 0 failed.



from ReactJS realtime search filter of array of arrays

No comments:

Post a Comment