I need to create a search bar in React that would show suggestions for a specific word. For example If I type t it would show 3 suggestions and the suggestions and whenever i remove “t” the suggestions will vanish. Also the suggestions have to come from an array no API. How do I implement this? I am really a starter in React and I badly need this help
I tried using states but couldn’t managed to achieve that result.
2
Answers
Ok. Here is an example of code that I created:
You can test this code using an array of suggestions like this:
And using the component like this:
You can use MUI’s Autocomplete Component. For a more custom approach, you can make a search result component which will render the search result. Make another state to store the search results which will be an empty array initially.
In the onChange function of your input, update your state with the text from your array using Javascript
.includes()
function.An example can be:
You can map through the suggestionArray to display the result in your suggestion component