Autocomplete Input in React

javascript react autocomplete input data feching
Autocomplete Input in React

Overview

This is the first lab in the series of cool React mini apps/components that we are going to build together. I have tried to keep it simple and at the same time informative enough so that you folks actually learn about how to create a custom autocomplete input box in React.

Features of the component

  1. There is an input box with placeholder
  2. On focussing on the input, a list of pokemons with their name and image appear in the div below.
  3. You can type something in the input and the list will get filtered accordingly
  4. On selecting an item in the list, the list disappears with the name of the pokemon in the input.
  5. Nice to have features:
    1. If the list of pokemons is visible, clicking on the input or any where in the page, the list should disappear and should reappear again when focussing on the input

 

Learning Objectives

In this lab, you will learn about different React concepts like hooks, creating a function component, data fetching in React, usage of array functions like map, fill, filter, etc.

 

To get the most out of this series:

You need to be at least acquainted with basic JS and React concepts. You will be able to understand everything if you have given atleast a day to learn React.

 

Code/Environment Setup:

Preferred Code Editor: VS Code,

Node version >= 12.0.0

Create a react project boilerplate using the create-react-app CLI or if you have npx installed on your system you can directly do npx create-react-app

To get npx on your system, run

npm install -g npx
npx create-react-app custom-autocomplete-react
cd custom-autocomplete-react
yarn start or npm start

and there you go!

You have your react project ready to be consumed and altered into something meaningful.

Fetching data for the autosuggest

You might have guessed till now, that we will be using the useEffect React hook here. As soon as the component is mounted, we will be fetching the pokemon data asynchronously.

For data, we will be consuming this API.

Note: For folks coming from the Class component world of React, useEffect will be used here as the componentDidMount function.

Let us fetch 20 pokemons and we will create a state called options.

Just below the searchText state declaration,

const [options, setOptions] = useState([]);

useEffect(() => {
    const pokemon = [];
    const promises = new Array(20)
      .fill()
      .map((v, i) => fetch(`https://pokeapi.co/api/v2/pokemon-form/${i + 1}`));
    Promise.all(promises).then(pokemonArr => {
      return pokemonArr.map(value =>
        value
          .json()
          .then(({ name, sprites: { front_default: sprite } }) => {
            console.log({ name, sprite })
            pokemon.push({ name, sprite })
          })
      );
    });
    setOptions(pokemon);
  }, []); 
// empty dependency array signifies that this will be called only once after the component has mounted

new Array(20).fill() will create an array of 20 elements, all undefined. I will be calling the api 20 times (sorry but that is how it has been configured). Resolving all the promises, I will set my options state to the pokemon array containing name of the pokemon and its sprite (image).

Because, we are logging the data in the console, you will be able to see the data in the browser console.

Discussion

3