Reputation: 37
Hi so I have some data that I want to search and filter through using hooks. I am able to get the initial list loaded but I don't know how to search the array and if the input text matches text in the array then display the array text that matches the input text. I tried using filter and stuff but am just confused as to how to put it all together. The data I need I can get by using props.data.map((e) => e.name)
import React, { useState } from "react";
import CharacterCard from "./CharacterCard";
import CharacterList from "./CharacterList";
export default function SearchForm(props) {
console.log(props.data.map((e) => e.name));
let hi = []
props.data.map((e) => hi.push(e.name))
const [search, setSearch] = useState('');
const check = () => {
if(search === ''){
return <CharacterCard data={props.data} />
} else if (hi.indexOf(search) === -1 ){
return <CharacterCard data={props.data} />
} else {
return <h1>{I want this to be anything that matches the input bot value}</h1>
}
}
let handleChange =(e) => {
setSearch(e.target.value)
}
return (
<section className="search-form">
<input type="text" onChange={handleChange} value={search} />
{check()}
</section>
);
}
Upvotes: 2
Views: 62
Reputation: 2854
You're on the right track, you just need to modify your check
function. This example will render a list of all names that have a partial match in the beginning of the name:
const check = () => {
// get array of all names in `props.data`
const names = props.data.map(e => e.name);
// this will filter out any names that do not start with the content of `search`
// leaving us with an array of matching names
const searchMatches = names.filter(name => name.startsWith(search));
// do something with the results `searchMatches`
// (this example returns a list of names)
return <ul>{searchMatches.map(name => <li key={name}>{name}</li><ul>
})
Upvotes: 1