Reputation: 415
I'm trying to create a search bar that filters out a set of data. The search function I made uses several states to filter results. When the search bar and results page are in the same class, the search function works but what I'm trying to do now is separate the search bar and display the search results on a separate page. Here's the state being set in the SearchBar class.
handleChange = (event) => {
this.setState({
names: event.target.value
})
}
The problem is I have no idea how to get the data stored in the SearchBar class to be displayed on the results page. Here's how I'm filtering the results on the results page.
const filteredData = data.filter(entry => (entry.name === (this.state.names))
This data is being filtered in the Search class but this.state.names
is being stored in the SearchBar class. This SearchBar class is being displayed on my header where users can search for whatever they want and after they press search, the results page appears. So how can I take the data stored in the SearchBar class and use it in a different class?
UPDATE: I tried passing in the state to the Search class in the render function but that causes the entire page to just freeze.
render() {
return (
<Search names = {this.state.names} />
)
}
Upvotes: 0
Views: 603
Reputation: 59
Not sure if I understood correctly but:
You can make a new component to store your data.
Then use this function (or similar) in onChange on that component
const filterData = (e) => {
const valueToCheck = e.target.value
let newArr = []
for(entry of data) {
// do the logic
//push the data you want into an array
newArr.push(entry)
}
setState(newArr)
}
Upvotes: 1
Reputation: 891
SearchBar should call onSearchResults([...]) callback and then PageResult
may accept those results, you need a component that orchestrate all.
const App = () =>{
const [results, setResults] = useState([]);
return (<>
<SearchBar onSearchChange={setResults}/>
{ results.length && <PageResult results={results}/> }
</>)
}
SearchBar will call props.onSearchChange(results)
with the filtered data. App component will react to that change and send those results to PageResult component
Upvotes: 0