How to Create Autosuggest Component using MUI and NextJS?

Autosuggest components are essential for enhancing user experience by providing real-time suggestions as users type. This aspect is especially important for searches in online shopping and when searching for favourite songs or movies on platforms like YouTube and Netflix. In these contexts, autosuggest components play a major role. This article will implement an autosuggest component and demonstrate its functionality.

Output Preview:

output preview

Prerequisites:

Approach

  • Create a new Next.js project using create-next-app and install the necessary libraries like Material-UI and Axios.
  • Develop the autosuggest component using MUI’s Autocomplete and TextField components. This component will manage its state and fetch suggestions dynamically.
  • Implement an API route in Next.js to handle fetching suggestions based on user input. Update the autosuggest component to use this API route.
  • Ensure the component is efficient and user-friendly by adding debounce to API calls, error handling, accessibility features, and custom styling.

Steps to Setup NextJS Application

Step 1: Create a NextJS application by using this command

npx create-next-app autosuggest-app

Step 2: Navigate to project directory

cd autosuggest-app

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install @mui/material @emotion/react @emotion/styled
npm install @mui/icons-material
npm i axios

Project Structure:

autosuggest project structure

The updated dependencies in package.json file will look like:

"dependencies": {
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5",
"@mui/icons-material": "^5.15.18",
"@mui/material": "^5.15.18",
"axios": "^1.7.2",
"next": "14.2.3",
"react": "^18",
"react-dom": "^18"
}

Example: Implementation to create auto-suggest component.

CSS
/* pages/autosuggest.module.css* */
.autocomplete {
  width: 300px;
  background-color: rgb(207, 205, 205);
}
JavaScript
//pages/autosuggest.js

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

const AutoSuggest = ({ suggestions }) => {
  const [inputValue, setInputValue] = useState("");
  const [selectedValue, setSelectedValue] = useState(null);

  return (
    <Autocomplete
      options={suggestions.map((suggestion) => suggestion.title)}
      value={selectedValue}
      onChange={(event, newValue) => {
        setSelectedValue(newValue);
      }}
      inputValue={inputValue}
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      renderInput={(params) => (
        <TextField {...params} label="Search" variant="outlined" />
      )}
    />
  );
};

export default AutoSuggest;
JavaScript
// pages/index.js

import React from "react";
import AutoSuggest from "./autosuggest";
const suggestions = [
  { title: "Option 1" },
  { title: "Option 2" },
  { title: "Option 3" },
];

const Home = () => {
  return (
    <div style={{ color: "black", backgroundColor: "white", height: "100vh" }}>
      <h1>Autosuggest Example</h1>
      <br />
      <h3>
        <AutoSuggest suggestions={suggestions} />
      </h3>
    </div>
  );
};

export default Home;

Step to Run Application: Run the application using the following command from the root directory of the project

npm run dev

Output:

Example 2: Implementation to Create Auto-suggest Component that fetches suggestions dynamically.

CSS
/* pages/autosuggest.module.css* */
.autocomplete {
  width: 300px;
}
JavaScript
//pages/autosuggest.js

import React, { useState, useEffect } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import axios from "axios";

const AutoSuggest = () => {
  const [inputValue, setInputValue] = useState("");
  const [suggestions, setSuggestions] = useState([]);

  useEffect(() => {
    if (inputValue) {
      axios
        .get(`/api/suggestions?q=${inputValue}`)
        .then((response) => {
          setSuggestions(response.data);
          console.log(response.data);
        })
        .catch((error) => {
          console.error("Error fetching suggestions:", error);
        });
    } else {
      setSuggestions([]);
    }
  }, [inputValue]);

  return (
    <Autocomplete
      options={suggestions.map((suggestion) => suggestion.title)}
      value={null}
      onChange={(event, newValue) => {
        console.log("Selected:", newValue);
      }}
      inputValue={inputValue}
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      renderInput={(params) => (
        <TextField {...params} label="Search" variant="outlined" />
      )}
    />
  );
};

export default AutoSuggest;
JavaScript
//pages/api/suggestions.js

export default function handler(req, res) {
  const { q } = req.query;
  const suggestions = [
    { title: 'Option 1' },
    { title: 'Option 2' },
    { title: 'Option 3' },
  ];
  const filtered = suggestions.filter(
      s => s.title.toLowerCase().includes(q.toLowerCase()));
  res.status(200).json(filtered);
}
JavaScript
// pages/index.js

import React from "react";
import AutoSuggest from "./autosuggest";


const Home = () => {
  return (
    <div style={{ color: "black", backgroundColor: "white", height: "100vh" }}>
      <h1>Autosuggest Example 2</h1>
      <br />
      <h3>
        <AutoSuggest />
      </h3>
    </div>
  );
};

export default Home;

Step to Run Application: Run the application using the following command from the root directory of the project( if already application running ignore this step ).

npm run dev

Output :

Best Practices

  • Debounce Input: Use a debounce function to delay making API calls when the user types quickly. This helps reduce the number of API requests.
  • Error Handling: Add error handling to manage problems like network issues or server errors during API calls.
  • Accessibility: Make sure the component is accessible by using the right ARIA attributes.
  • Styling: Customize the component to fit your application’s design.

Conclusion

Creating an autosuggest component with MUI and Next.js requires setting up your project, building the component, and fetching data dynamically. Following best practices ensures the component is responsive, accessible, and user-friendly. This improves the user experience by offering relevant suggestions as users type, making your application more intuitive and efficient.