When using a computer, you want the computer to do exactly what you want when and how you need it. Finding a the right file or post quickly is essential to boosting productivity. Search engines are extremely useful in finding the data users need in a shorter amount of time. My objective for this post is to explain how I make simple search engines for sites in JavaScript and React.
Grabbing the Data
For this example we’re gonna grab data from a .json file using the fetch function. The data grabbed from the .json is stored in an array that we can use to display to our screen.
/* App.js */
import React, { useState, useEffect } from "react"
import Header from "./Header"
import SearchBar from "./SearchBar"
import DataContainer from "./DataContainer"
function App() {
const [data, setData] = useState([])
useEffect(() => {
fetch(url)
.then(resp => resp.json())
.then(dataArray => setData(dataArray))
},[])
return (
<>
<Header />
<SearchBar />
<DataContainer data={data}/>
</>
)
}
export default App
Create a useState
useState is a react tool that can make your web app very dynamic. The useState variable updates everything that is using that variable anytime it is changed. We can use that to change the data whenever the input field is changed.
/* App.js */
const [searchString, setSearchString] = useState('')
Then we can create a function to change searchString whenever you change the text input.
/* App.js */
const handleSearch = (string) => {
setSearchString(string)
}
...
<SearchBar handleSearch={handleSearch} />
/* SearchBar.js */
function SearchBar({handleSearch}) {
return (
<div>
<input
onChange={handleSearch(e.target.value)}
type="text"
/>
</div>
)
}
export default SearchBar
Every time the input is changed, handleSearch updates our useState to the same value.
We can use data to create a separate array that changes every time you enter a new query. You can do this by using .filter() and use .includes() on the strings to filter them. Since we used a useState, the array will change after we change the input.
/* App.js */
const searchArray = data.filter((item) => {
return item.name.toLowerCase().includes(searchString.toLowerCase())
})
Make sure to create the searchArray after the handleSearch or else the data will still be showing the previous input.
/* App.js */
<DataContainer data={searchArray}/>
Lastly we pass the data to our DataContainer component. Now all our data has been filtered and is ready to be used in DataContainer.
Top comments (0)