#react
    #javascript

Create an auto-suggest field with React

Auto-suggest in the real world

An auto-suggest input field has some wonderful uses in the real world, including

  • allowing a user to more quickly get to the end result of what they're typing
  • save users the effort of typing out the entirety of what they're looking for
  • indicate to the user other possible options for the field that they might not have known about
  • indicate to the user what's a valid input versus not

You interact with an auto-suggest field probably everyday if you're searching on Google. One of the most prominent places where auto-suggest is used is in their search bar like below

It can be really useful for users and save them time! Let's get to building one with React.

It'll end up looking like this

image.png


Setting up the auto-suggestion app

We'll build out a small React application using shards-react for a nice looking input field and list of auto-suggestion items.

You can create a new React application however you'd like or you can also follow with the live site listed in this post.

Either way, you can refer to the code in the live site as we build out the auto-suggestion through to its final iteration.

Once you've got your project going, you can install the shards-react package using

npm i shards-react bootstrap shards-ui

This just installs shards-react and some additional dependencies, including Bootstrap.

Lastly, into your App.tsx file, or wherever your main application code will go, add these lines

import { FormInput } from "shards-react";
import { ListGroup, ListGroupItem } from "shards-react";
import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

This imports the CSS for Bootstrap and shards-react for use in your app.

It also imports the two components we'll use for building the auto-suggestion functionality — including the input field where text will be entered, and the list of results that matched the entered text.


Building out the component

Our auto-suggest application will let user type in a technology and select it as their favorite tech. As they type, we'll display a list of technologies that match the term they entered in the input field.

Outside the component, we'll define a list of technologies that our user can search through

const technologies = [
  'react',
  'html',
  'sass',
  'css',
  'node',
  'javascript',
  'java',
  'vue',
  'nextjs',
  'angular',
];

and then, inside our component, we'll define a few state variables

  • a state variable for the entered search term
  • a state variable for the list of technologies that include the search term
  • a state variable for the selected technology
const Application = () => {

  const [favorite, setFavorite] = useState('');
  const [input, setInput] = useState('');
  const [matchingResults, setMatchingResults] = useState([]);
  ...

  return (
  <div className="app">
      ...
    </div>
  );

The matchingResults variable will hold an empty list at first, and that's because there can possibly be more than 1 matching technology for a search term.

For example, a search term of "java" would match with both "java" and "javascript".


Listen for changes on the input field

A big part of an auto-suggest feature is that is should attempt to find suggestions for a given search term any time a key stroke occurs on the input field.

This is so you can quickly provide suggestions to the user as they enter their query.

So for example, given our above list, if a user enters the search term "j", then the auto-suggestions should be "java", "javascript".

As they continue to type, the suggestions get narrowed down further with their search term, or they can pick one of the suggestions and be done with their search.

We can do all of the above here in the onChange event of the input field where the user is entering their search term.

Here's how that will look

...
  const onChangeHandler = (event) => {
    const { value } = event.target;
    setInput(value);

    // Get the list of technologies that include the search term
    const resultMatches = technologies.filter((tech) => {

      // Handle when the input value is an empty string
      if (value.trim().length === 0){
        return false;
      }

      return tech.includes(value.toLowerCase());
    });

    setMatchingResults(resultMatches);
  };

    setMatchingResults(resultMatches);
  };
...

In the above, we're getting the current value of the input field and checking if its lowercase value is one of the technologies in our predefined technologies list. If it is, then we can add it to our set of matching results.

In just one more step, that list of matching results will be displayed right below our input field.


Handling when a auto-suggestion is clicked

We'll also want to make each of the matching results clickable, so that a user can actually pick from the matches.

When one of the results is clicked, we'll want to do the following

  • display the selected result in our "Search for your favorite technology:" string
  • clear out the search term from the input field, since the user has found what they're looking for
  • clear out the list of result matches, since they're no longer needed

We can code that up in a few lines

  const onResultClick = (result) => {
    setFavorite(result);
    setMatchingResults([]);
    setInput('');
  };

And we can finish up the rest of the application with

  ...
  return (
    <div className="app">
      <h5>Auto Suggest Example</h5>

      {/** Display the input field */}
      <p>Search for your favorite technology: {favorite}</p>
      <FormInput 
        placeholder={"Enter your query here"} 
        value={input}
        onChange={onChangeHandler}
      />

      {/** Display any matches to the entered search term */}
      {matchingResults.length > 0 && 
        <ListGroup>
          {matchingResults.map((match) => {
            return (
              <ListGroupItem
                onClick={() => onResultClick(match)}
              >
                {match}
              </ListGroupItem>
            );
          })}
        </ListGroup>
      }
    </div>
  );

The above will go at the end of our application.

We're using the FormInput component provided to us by shards-react for the input field that the user ends up typing into. A placeholder value of "Enter your query here" is shown when the user hasn't entered a search term yet, and we've set the onChange prop of the component to call our onChangeHandler function we defined in the previous section.

Right below that, when the list of matching results isn't empty, we're displaying the ListGroup component to hold all of the available matches we've found for our user's search term.

Lastly, we're iterating through the available list of match results with matchingResults.map((match) => ... to display a ListGroupItem for every matching result.

This is also a component we're using from shards-react, which is helping us out with giving us a simple but slick user interface.

Hopefully, this post has provided you with a solid foundation for building auto-suggest functionality for your projects.

Check out the code and live site for the full running application!


zerochass

practical and goal-oriented resources

learn by doing. enjoy what you do.