How to Create React Material UI Autocomplete Widget in React

Autocomplete is a UI widget that provides suggested options through a text input field. Modern web applications use this module to enhance their data search.

In this post, you will learn how to simply create autocomplete widget in React Js application using React Material UI package.

In UI, Autocomplete module permits the browser to forecast the value. Ideally, when the user begins typing in the text input field, the browser manifests certain options below the search field. More likely based on keywords typed in the field.

Throughout this React Material UI Autocomplete tutorial: we will teach you how to create a React AutoComplete text-box component. It will solely display a list of suggestions just below the search input box.

Setting Up React Project

The primary goal of this article is to share how to add autocomplete in React.

In contrast, we will begin building a new React project with below command.

npx create-react-app react-blog

Add React Material UI

The React MUI comes with custom user-interface widgets that drastically reduce the UI component development time.

Use the npm command to install and use the MUI package in React.

npm install @mui/material @emotion/react @emotion/styled @fontsource/roboto

You have to now look for App.css file make sure to open it and add the following entries.

@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");

@import "@fontsource/roboto/300.css";
@import "@fontsource/roboto/400.css";
@import "@fontsource/roboto/500.css";
@import "@fontsource/roboto/700.css";

Build New Component

We need to get into src/ folder, here you have to make the features folder along with Home.js file.

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Build Autocomplete Component

The most common example of Autocomplete is a Google Search bar. It gets a lot of daily searches; comparatively, it displays millions of suggestions daily. It is a prime example of top-notch user-friendly suggestions.

In this step, we will see how to implement autocomplete module in a function component.

Place code inside the features/Home.js file.

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import CircularProgress from "@mui/material/CircularProgress";

function sleep(delay = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
}

export default function Home() {
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const loading = open && options.length === 0;

  React.useEffect(() => {
    let active = true;

    if (!loading) {
      return undefined;
    }

    (async () => {
      await sleep(1e3); // For demo purposes.

      if (active) {
        setOptions([...topFilms]);
      }
    })();

    return () => {
      active = false;
    };
  }, [loading]);

  React.useEffect(() => {
    if (!open) {
      setOptions([]);
    }
  }, [open]);

  return (
    <Autocomplete
      id="asynchronous-demo"
      sx={{ width: 300 }}
      open={open}
      onOpen={() => {
        setOpen(true);
      }}
      onClose={() => {
        setOpen(false);
      }}
      isOptionEqualToValue={(option, value) => option.title === value.title}
      getOptionLabel={(option) => option.title}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />
  );
}

// Top films as rated by IMDb users. http://www.imdb.com/chart/top
const topFilms = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Schindler's List", year: 1993 },
  { title: "Pulp Fiction", year: 1994 },
  {
    title: "The Lord of the Rings: The Return of the King",
    year: 2003,
  },
  { title: "The Good, the Bad and the Ugly", year: 1966 },
  { title: "Fight Club", year: 1999 },
  {
    title: "The Lord of the Rings: The Fellowship of the Ring",
    year: 2001,
  },
  {
    title: "Star Wars: Episode V - The Empire Strikes Back",
    year: 1980,
  },
  { title: "Forrest Gump", year: 1994 },
  { title: "Inception", year: 2010 },
  {
    title: "The Lord of the Rings: The Two Towers",
    year: 2002,
  },
  { title: "One Flew Over the Cuckoo's Nest", year: 1975 },
  { title: "Goodfellas", year: 1990 },
  { title: "The Matrix", year: 1999 },
  { title: "Seven Samurai", year: 1954 },
  {
    title: "Star Wars: Episode IV - A New Hope",
    year: 1977,
  },
  { title: "City of God", year: 2002 },
  { title: "Se7en", year: 1995 },
  { title: "The Silence of the Lambs", year: 1991 },
  { title: "It's a Wonderful Life", year: 1946 },
  { title: "Life Is Beautiful", year: 1997 },
  { title: "The Usual Suspects", year: 1995 },
  { title: "Léon: The Professional", year: 1994 },
  { title: "Spirited Away", year: 2001 },
  { title: "Saving Private Ryan", year: 1998 },
  { title: "Once Upon a Time in the West", year: 1968 },
  { title: "American History X", year: 1998 },
  { title: "Interstellar", year: 2014 },
];

Register Home Component

In this step we are going to dive into the App.js file that you can find in src directory.

You have to import the Home component in App component.

import React from "react";
import Home from "./features/Home";

function App() {
  return (
    <div>
      <h2>React Material UI Autocomplete Example</h2>
      <Home />
    </div>
  );
}

export default App;

Start React Server

By using the React Material UI library we have eliminated the UI component creation time.

From developers outlook the MUI library provides greater flexibility and usability.

So now the time is to start the application using the given command and check it on the browser.

npm start
http://localhost:3000

How to Create React Material UI Autocomplete Widget in React