How to Create Autosuggest Component using MUI and NextJS?
Last Updated :
04 Jul, 2024
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 previewPrerequisites:
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 structureThe 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.
Similar Reads
How To Create Dynamic Breadcrumbs Component in NextJS?
Breadcrumbs are an essential navigational aid in web applications, especially in multi-level hierarchies. In a Next.js application, creating a dynamic breadcrumbs component can enhance the user experience by providing clear navigation paths. In this guide, we'll walk through the process of building
3 min read
How To Create A Custom MUI Search Bar Component In NextJS?
Creating a custom Material-UI (MUI) search bar in the NextJS application is a great way to enhance the user experience by providing seamless and stylish search functionality. In this article, we will guide you through the steps to create a custom MUI search bar component in a Next.js project.Prerequ
3 min read
How to create jQuery UI Autocomplete ?
In this article, we are going to see how to make an input filed (input text) autocomplete. To do this, we use the jquery UI library. Here we take the input field where users have the ability to easily find and select from a pre-populated list of values by typing in search terms and filters. Steps: I
2 min read
How to Create Todo App using Next.js ?
In this article, we will create a to-do application and understand the basics of Next.js. This to-do list can add new tasks we can also delete the tasks by clicking on them.Next.js is a widely recognized React framework that eÂnables server-side rendering and enhanceÂs the developmeÂnt of interacti
4 min read
How to add Draggable Components in Next.js ?
In this article, we are going to learn how we can add Draggable Components in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components
2 min read
How to add Search Feature in Next.js using Algolia ?
Adding a search feature to your Next.js application can greatly enhance user experience by providing fast and relevant search results. Algolia is a powerful search-as-a-service solution that integrates seamlessly with Next.js to offer instant, full-text search capabilities. In this article, we will
3 min read
ReactJS UI Ant Design AutoComplete Component
Ant Design Library has this component pre-built, and it is very easy to integrate as well. AutoComplete Component is used for auto-completing the free text value with the option value. We can use the following approach in ReactJS to use the Ant Design AutoComplete Component. AutoComplete Methods: bl
3 min read
How to add Filters in Next.js using Algolia ?
In this article, we will learn How we can add filters in the NextJS project using Algolia. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS compo
4 min read
How to Get query params using Server component in Next.js ?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. We will discuss different approaches to get query params using the server comp
3 min read
How to add Pagination in Nextjs using Algolia ?
Adding pagination to a Next.js application with Algolia involves fetching and displaying paginated search results from Algoliaâs API. This setup provides an efficient way to handle large datasets by loading data in chunks. In this article, we will learn How we can add pagination in the NextJS projec
2 min read