How to Create Autocomplete Dropdown in React Application

In this article, we will learn how to create  Autocomplete Dropdown in React Application using Material UI.

Prerequisites of React

  • Familiarity with the HTML, JavaScript.
  • node.js installed
  • Basic knowledge of React JS
  • Visual Studio Code

Create React Project

To create a React app, use the following command in the terminal.

npx create-react-app matui

Open the newly created project in Visual Studio Code, and install Material-UI; run the following command in your React project's root directory.

npm install @material-ui/core

Now right-click on the src folder and create a new component named 'Autocomplete.js'. We will create a simple modal popup using material UI. Import the following component from Material UI in the Autocomplete.js file.

import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

Now, add the following code in the Autocomplete.js file.

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

export default function Autocompletedemo() {
  return (
    <div className="container mt-5">
                <h2>How to Create Autocomplete Dropdown in React Application</h2>
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={topFilms}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Select Moive" />}
    />
    </div>
  );
}

const topFilms = [
  { label: 'The Shawshank Redemption', year: 1994 },
  { label: 'The Godfather', year: 1972 },
  { label: 'The Godfather: Part II', year: 1974 },
  { label: 'The Dark Knight', year: 2008 },
  { label: '12 Angry Men', year: 1957 },
  { label: "Schindler's List", year: 1993 },
  { label: 'Pulp Fiction', year: 1994 },
]

In the above code, we have added material ui autocomplete and created dummy data to show in the autocomplete dropdown.

Now, import the Autocomplete component in the src/App.js file.

import logo from './logo.svg';
import './App.css';
import Autocompletedemo from './Autocomplete'
function App() {
  return (
    <div className="App">

      <Autocompletedemo/>
    </div>
  );
}

export default App;

Run the project using the 'npm start' command and check the result.

Output Image

Summary

This article provides a step-by-step guide on creating Autocomplete Dropdown in React application using the Material UI library.