Home > Enterprise >  Limit the number of results for autocomplete component?
Limit the number of results for autocomplete component?

Time:04-27

I'm using React JS and I've created an autocomplete component that returns a list of results.
Here's my code for the autocomplete :

const [pokedexMatch, setPokedexMatch] = useState([]);

const searchPokedex = (text) => {
  if (!text) {
    setPokedexMatch([]);
  } else {
    let matches = pokedex.filter((pokedex) => {
      const regex = new RegExp(`${text}`, "gi");
      return pokedex?.name?.match(regex);
    });
    setPokedexMatch(matches);
  }
};

Here's a working sandbox with some dummy text below. As you can see, when you type a single letter it returns a lot of results and move the text below the results.
What I'd like to do is limit the number of results to 5 and make the list of results go above the text (I guess that I should use absolute positioning but I'd like to know if there is another method without absolute positioning) ?

CodePudding user response:

To limit your results to 5, use simple Javascript!

setPokedexMatch(matches.slice(0, 5));

For the positioning part of your question, you're on the right track - you can use absolute positioning of a div with a white background to make the results appear to be "above" the text.

EDIT: I've updated your sandbox here and made some very minor changes.

  • When you map over an array, make sure you include a key prop. Read more here.
  • I added the slice method to limit your results to 5
  • I added a simple above class to the parent <ul /> element to make the results appear "above" the text. This is just one way to accomplish this, I'll leave it to you to style it better if you'd like.
  • Related