ReactHustle

How to Create A React Autosuggest Component using MUI and NextJS

Jasser Mark Arioste

Jasser Mark Arioste

How to Create A React Autosuggest Component using MUI and NextJS

Introduction #

React is a popular JavaScript library for building user interfaces, and one of its strengths is the vibrant ecosystem of community-contributed components. An <AutoSuggest/> component is essential in modern web applications, providing users with a convenient way to search and select items from a list as they type. In this tutorial, we'll walk you through creating a React AutoSuggest component by using MUI and NextJS. By the end of this article, you'll have a better understanding of React and how to build custom components.

Final Output #

Here's the final output of what you'll be making:

React Autosuggest Demo

Prerequisites #

Before we start building our React AutoSuggest component, make sure you have the following tools and knowledge:

  1. Node.js and npm (Node Package Manager) installed on your computer.
  2. A code editor (e.g., Visual Studio Code).
  3. Basic knowledge of React.

Setting Up Your React Project #

To get started, create a new NextJS project using create-next-app or any other method you prefer. Open your terminal and run the following command:

npx create-next-app@latest --app --ts react-autosuggest-component-mui

This command will create a new NextJS project named "react-autosuggest-component-mui".

Installing Dependencies #

Next, let's install MUI since we'll need its AutoComplete component later on. Run the following commands on the same terminal as before.

cd react-autosuggest-component-mui
yarn add @mui/material @emotion/react @emotion/styled

Next, let's install a utility library (usehooks) that will be useful later on:

yarn add usehooks-ts

Creating the AutoSuggest Component #

Now, let's create our AutoSuggest component. Inside your project folder, navigate to the `src` directory, create a new folder `components`, and create a new file called `AutoSuggest.tsx`. In this file, we'll define our AutoSuggest component.

"use client";
import {
  Autocomplete,
  ListItem,
  ListItemAvatar,
  ListItemText,
  TextField,
} from "@mui/material";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { useDebounce } from "usehooks-ts";

// define types
type Suggestion = {
  title: string;
  description: string;
  thumbnail?: string;
};

type SearchResult = {
  products: Suggestion[];
};

function AutoSuggest() {
  const [query, setQuery] = useState("");
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);

  const [loading, setLoading] = useState(false);
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;
    setQuery(input);
    setSuggestions([]);
    setLoading(true);
  };

  const debouncedQuery = useDebounce(query, 600);

  // logic for fetching suggestions
  useEffect(() => {
    if (!debouncedQuery) {
      setLoading(false);
      return;
    }
    // call your backend API for fetching suggestions. We use dummyjson.com as an example. For more information, go to: https://dummyjson.com/docs/products
    fetch(
      `https://dummyjson.com/products/search?q=${debouncedQuery}&select=title,description,thumbnail`
    ).then(async (res) => {
      const json = (await res.json()) as SearchResult;
      setSuggestions(json.products);
      setLoading(false);
    });
  }, [debouncedQuery]);

  return (
    <Autocomplete
      options={suggestions}
      onInputChange={(e) => {}}
      getOptionLabel={(option) => option.title}
      filterOptions={(x) => x} //disable default autocomplete behavior
      renderOption={(props, option) => {
        return (
          <ListItem key={option.title}>
            <ListItemAvatar
              sx={{ height: 100, width: 100, position: "relative" }}
            >
              <Image
                src={option.thumbnail!}
                alt={option.title}
                unoptimized
                fill
                style={{ objectFit: "cover" }}
              />
            </ListItemAvatar>
            <ListItemText
              primary={option.title}
              secondary={option.description}
            />
          </ListItem>
        );
      }}
      loading={loading}
      loadingText={"Searching..."}
      noOptionsText="Search for something..."
      fullWidth
      renderInput={(params) => (
        <TextField
          {...params}
          variant="outlined"
          size="small"
          placeholder="Search..."
          onChange={handleInputChange}
        />
      )}
    />
  );
}

export default AutoSuggest;
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798

In this component, we use React hooks (useState) to manage the component's state (lines #25-28). We also have an input field for typing. This is defined in the renderInput prop (lines 83-91). We also have a list of suggestions that will be displayed as the user types.

In lines 36-52, we also implemented the logic to fetch and filter suggestions based on the user's input. We fetch suggestions from DummyJSON API. We use the useDebounce hook from usehooks-ts, to limit the number of requests sent to the API.

Integrating the AutoSuggest Component #

To use the AutoSuggest component in your application, import it into your desired component and render it. For example:

// /app/page.tsx

import AutoSuggest from "./components/AutoSuggest";

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <AutoSuggest />
    </main>
  );
}
1234567891011

Conclusion: #

In this tutorial, you learned how to create a basic React AutoSuggest component from scratch. While this example provides a foundation, you can further enhance and customize your AutoSuggest component to suit your specific requirements.

This component can be a valuable addition to your web applications, making them more user-friendly and efficient. Feel free to explore additional features like keyboard navigation, accessibility, and more to make your AutoSuggest component even more robust. Happy coding!


Recommended Books #

If you want to improve in your react skills, checkout these books!

Credits: Image by Peter H from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle