Learn how to easily incorporate a drop-down list into the material-UI Search component within the navbar to enhance the search results

I integrated a Material UI search bar into my React app's navbar following the instructions from the official documentation on MUI. However, the article does not provide any guidance on how to add a dropdown list when selecting the search input field.

I tried various methods, including using Menu and List components from MUI to implement the dropdown menu, but none of them worked for me. Can someone please help me figure out how to add a dropdown list that matches the width of the search bar to display search results? You can also check out the codesendbox link for reference.

The code in my App.js:

import "./styles.css";
import * as React from "react";
// Rest of the code...

Thanks in advance!

Answer №1

As per the suggestion from @rupesh patil, it is recommended to switch to Autocomplete. Additionally, you can consider displaying a List under the Search input when the search input is focused, and then utilize the keyup event to manually search for results.

import "./styles.css";
import * as React from "react";
import { styled, alpha } from "@mui/material/styles";
import Box from "@material-ui/core/Box";
import InputBase from "@mui/material/InputBase";
import SearchIcon from "@mui/icons-material/Search";

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

const options = ['Option 1', 'Option 2'];
const Search = styled("div")(({ theme }) => ({
  position: "relative",
  borderRadius: theme.shape.borderRadius,
  backgroundColor: alpha(theme.palette.common.black, 0.15),
  "&:hover": {
    backgroundColor: alpha(theme.palette.common.black, 0.25)
  },
  marginTop: "5px",
  marginLeft: 0,
  width: "100%",
  [theme.breakpoints.up("sm")]: {
    marginLeft: theme.spacing(1),
    width: "auto"
  }
}));

const SearchIconWrapper = styled("div")(({ theme }) => ({
  padding: theme.spacing(0, 2),
  height: "100%",
  position: "absolute",
  pointerEvents: "none",
  display: "flex",
  alignItems: "center",
  justifyContent: "center"
}));
const StyledInputBase = styled(InputBase)(({ theme }) => ({
  color: "red",
  "& .MuiInputBase-input": {
    padding: theme.spacing(1, 1, 1, 0),
    // vertical padding + font size from searchIcon
    paddingLeft: `calc(1em + ${theme.spacing(4)})`,
    transition: theme.transitions.create("width"),
    width: "100%",
    [theme.breakpoints.up("sm")]: {
      width: "12ch",
      "&:focus": {
        width: "20ch"
      }
    },
    [theme.breakpoints.down("sm")]: {
      width: "0ch",
      "&:focus": {
        width: "12ch"
      }
    }
  }
}));

export default function ControllableStates() {
  const [value, setValue] = React.useState(options[0]);
  const [inputValue, setInputValue] = React.useState('');
  return (
    <div className="App">
      <div>
        <nav
          id="navbar"
          className=" pt-0 pb-0 ps-3 container-row navbar-dark navbar navbar-expand-lg nav-div fixed-top"
        >
          <div className="container">
            <div className="navbar-brand">
              <h1 className="logo-text mt-1 text-dark">project logo</h1>
            </div>
            <div className="nav-list">
              <ul className="nav navbar-nav ms-auto mb-2 mb-lg-0">
                <React.Fragment>
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      textAlign: "center"
                    }}
                  >
                    <Search>
                      <SearchIconWrapper>
                        <SearchIcon />
                      </SearchIconWrapper>
                      {/* <StyledInputBase
                        placeholder="Search Organization ..."
                        inputProps={{ "aria-label": "search" }}
                      /> */}
                       <Autocomplete
                        value={value}
                        onChange={(event, newValue) => {
                          setValue(newValue);
                        }}
                        inputValue={inputValue}
                        onInputChange={(event, newInputValue) => {
                          setInputValue(newInputValue);
                        }}
                        id="controllable-states-demo"
                        options={options}
                        sx={{ width: 300 }}
                        renderInput={(params) => <TextField {...params} label="Search Organization ..." />}
                      />
                    </Search>
                  </Box>
                </React.Fragment>
              </ul>
            </div>
          </div>
        </nav>
      </div>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to obtain the value of TR in JavaScript?

Objective: Extract the value "2TR" from "MARSSTANDGATA132TR" using JavaScript. Need to determine the location of the digit 2 within the extracted string. Issue: Uncertain about the correct syntax to achieve this task. Additional Details: *The cha ...

Updating the state does not reflect on the user interface

I'm a beginner in React and I've encountered an issue that I can't seem to figure out. I created a Component called ShoppingCart which is supposed to display all the products added to the cart: ShoppingCart.jsx file: import React, { Compo ...

Utilizing an external JavaScript file for developing applications on Facebook

I am looking to incorporate external JavaScript into my Facebook application development. Specifically, I am hoping to utilize the Ajax tab feature in my application. ...

Tips for setting a data-attribute on the body tag using the current route name in Vue

I have been considering adding a data-attribute to the body of my vue-app that would display the current route's name. I prefer not to utilize the vue-body-class package and want to keep it simple. Currently, I am implementing this in each of my main ...

Looking to prevent printing and saving a webpage directly from the file menu using JQUERY or JavaScript

I am in need of assistance to find a code that can disable the ability to print and save a webpage using JQUERY or JAVASCRIPT ...

The failure of the meteor reactiveVar to update is causing discrepancies in the displayed

I am currently developing a meteor application and making use of the reactivity feature to enable automatic updates of results on the DOM when they are available or upon update. Below is a snippet of my code: Template.message.helpers profession: ...

Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there&apo ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

There was an issue with the vue-server-renderer where the render function or template was not defined in the component

In my project with Vue 2.7 and webpack4 for SSR, I encountered an error message stating: render function or template not defined in component: anonymous. This issue arises under the following circumstances: When using a child component. <template> ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

Encountering a MUI Error when attempting to import through the Portal

I encountered an issue when trying to import the Portal from mui import {Portal} from @mui/base/Portal; When importing {Portal} from @mui/base/Portal; I'm receiving an error on this line. It seems that mui has released a new version of mui/base Any s ...

Tips for adjusting the scrollbar in Tailwind (next.js/react)

Having trouble changing the appearance of my scrollbar in a single page application using Tailwind (react/next). I've attempted to create custom CSS for the first div in my index file, like so: <div className="no-scroll"> <<< ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

Transitioning a NPM project to the Apache server

Recently, I successfully managed to run a simple example project by following these steps: I downloaded and installed Node.js for windows x64. I then used Git to clone the project from https://github.com/BretCameron/three-js-sample.git Next, I ran t ...

issues with the styling and scripts within the jsp document

During my project work, I encountered an issue with the front end as shown in the image below. Upon loading the project, all styles and scripts disappear completely. How can I resolve this issue promptly? I attempted to update the jQuery version by replac ...

Interactive sliding panel in Material Design UI

I am experiencing an issue with the Swipeable drawer feature from Material UI. In a normal Drawer, it is not necessary to add a function for onOpen. So my question is, what should I include there? container={container} variant=" ...

In the realm of Node.js and Express, an error has been thrown: "Router.use() cannot function without a middleware component, yet received a + gettype(fn)."

While developing an application with Node.js, I encountered the following error: throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^ TypeError: Router.use() requires a middleware function but got a ...

Angular Placeholder Positioned at the Top

Hello, I am a beginner in Angular and need to create an input field that looks like this: Everything is going fine except for the Vorname placeholder at the top. How can I place it there? Currently, I am utilizing Angular Materials. <div class='g ...