skip to Main Content

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


  1. Ok. Here is an example of code that I created:

    import React, { useState } from "react";
    
    // A component that receives an array of suggestions as a property
    function SearchBar({ suggestions }) {
      // A state to store the input value
      const [input, setInput] = useState("");
    
      // A function to update the input state when it changes
      const handleChange = (event) => {
        setInput(event.target.value);
      };
    
      // A function to select a suggestion when it is clicked
      const handleClick = (suggestion) => {
        setInput(suggestion);
      };
    
      // A method to filter the suggestions that match the input value
      const filteredSuggestions = suggestions.filter((suggestion) =>
        suggestion.toLowerCase().includes(input.toLowerCase())
      );
    
      // A method to render the suggestions in a list
      const renderedSuggestions = filteredSuggestions.map((suggestion) => (
        <li key={suggestion} onClick={() => handleClick(suggestion)}>
          {suggestion}
        </li>
      ));
    
      return (
        <div className="search-bar">
          <input type="text" value={input} onChange={handleChange} />
          <ul className="suggestions">{renderedSuggestions}</ul>
        </div>
      );
    }
    
    export default SearchBar;
    

    You can test this code using an array of suggestions like this:

    const suggestions = ["test", "text", "screen", "keyboard", "phone"];
    

    And using the component like this:

    <SearchBar suggestions={suggestions} />
    
    Login or Signup to reply.
  2. 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:

    const [text, setText] = useState('')
    const [suggestion, setSuggestion] = useState([])
    
    const suggestionArray = [...] //array to store all your suggestions
    
    const handleChange = e => {
      const tempText = e.target.value
      setText(tempText)
      
      if (tempText.trim().length) { //checking if input has some text or not
        const tempArr = suggestionArray.filter((element) => element.toLowerCase().includes(tempText.toLowerCase()));
        setSuggestion(tempArr)
      }
    }
    
    return <></> //JSX to display searchbar and suggestion
    

    You can map through the suggestionArray to display the result in your suggestion component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search