Creating a “real-time” search engine in React/Redux using Hooks (without a Submit button).
The app I was working on involved a collection of games I had seeded from an API. Using that library, I wanted the User to be able to search for a game title, and for each keystroke, the user can see the number of possible matches dwindle before their eyes, until they come upon the title (or titles) in question.
I started with a SearchContainer.js that will house both my search tool, as well as any Games that are rendered from the search . Import the two Hooks from their respective libraries, as well as any other components you may need. In this case, I’m going to render any Game that shares the same title as the search field.
We are going to be comparing two sets of data, so let’s take care of our search field first. We can put this data in our local state, which we’ll call searchData with a default value of an empty string. setSearchData will be updated with every keystroke.
For our field, we’ll create a basic form field within our return. Any thing typed into the text box will trigger the onChange event handler and send any and all updated values to the handleChange function.
Lastly (for the user input side), you need to update the local state (searchData) with whatever the user has typed in. And you will do that with the handleChange function.
Great! Now we have usable user input to search with. To quickly recap so far, we created a local state using the useState hook. We populated that state using a combination of a form field, onChange event listener, handleChange function, and the useState hook to populate our local state with that data.
Great! Almost done. Now we just need to compare our local state to some element within our global state. In this case, I just need the title from all the games in my library. Since my library is in the global state (thanks to Redux), I can access it from anywhere in my app by using the useSelector Hook.
First, we can define all the games from our global state using a constant variable (allgames). Then, we’ll filter through all those games, specifically their names (g.name) in lower case format, and compare it to the data that we entered into our search field (in lower case, naturally). Anything that filtered will be defined by a new variable — in this case,
gameNames is a constantly changing array of objects, hence the
Huzzah! You’ve done it!
Well, you can take those individual games, or any pieces of them that you need, and render it right there on the page. I do so by mapping my
gameNames array and creating a new <Game /> component for each one that existed. It makes for a nice picture to see all of your choices whittle down to a small few.
FINISHED PRODUCT: typing in “R” — “O” — “O”