How to Create Autosuggest Component using MUI and NextJS? - GeeksforGeeks (2024)

Last Updated : 29 May, 2024

Improve

Improve

Like Article

Like

Report

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:

How to Create Autosuggest Component using MUI and NextJS? - GeeksforGeeks (1)

output preview

Prerequisites:

  • NodeJS & NPM
  • React
  • Next.Js

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:

How to Create Autosuggest Component using MUI and NextJS? - GeeksforGeeks (2)

autosuggest project structure

The updated dependencies inpackage.jsonfile 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.jsimport 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.jsimport 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.jsimport 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.jsexport 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.jsimport 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.



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

How to Create Autosuggest Component using MUI and NextJS? - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 5589

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.