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

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

Is there a way to decrease the padding within the table cells when using material-react-table?

How can I adjust the padding in table cells with class names such as: MuiTableCell-root MuiTableCell-body MuiTableCell-sizeMedium css-ny9njj-MuiTableCell-root I am currently using version 1.14.0 of material-react-table. I have searched the documentation b ...

Is there a way for me to find out where I imported my React JS component?

During my work on a React JS project, I decided to delete a component. However, after some time, an error appeared indicating that the same component was previously imported somewhere else as well. Is there a way to quickly identify where I have imported ...

What is the best method for converting a list tag into an array of objects with XPath?

I am attempting to extract the ordered list and generate an array of list tags along with their content. I have experimented with different paths, such as: //li[div/@class="business-info"] //li[div[@class="business-info"]] //li[descendant::div[@class="bu ...

What might be causing Flex not to function properly on my personalized landing page?

I attempted to create a basic landing page featuring an image background with a logo, button, and a row of 4 images displayed side by side using Flex. However, for some reason, the Flex is not functioning properly for the row of images. Here is the code s ...

Turn off CSS scroll snapping past a specific threshold

Hey there! I have a total of 7 sections in my layout. The first 4 sections are all CMYK, while the last 3 are RGB. My current challenge is trying to prevent scroll snapping on the RGB sections. The issue arises when I apply scroll-snap-align: start; to t ...

Adjusting the line height of an inline-block div causes surrounding inline-block siblings to shift downward

As I venture into exploring the line-height property, I came across information on MDN which stated: For non-replaced inline elements, it determines the height used in calculating the line box height. However, in this scenario, when I set the line-heigh ...

What is the best way to add a gradient background image to a container that also has margins?

I am currently working on a push menu that shifts the main content container by adding margin-left to it. I am aiming to achieve a background image effect similar to what is seen on . Here is the progress I have made so far in my codepen: https://codepen ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

Error encountered: Unable to locate the module './reportWebVitals' in the directory 'C:UsersRobert LangdonDocumentsMERNReact1tutsrc'. The webpack compilation process resulted in 1 error

Hello everyone, I'm completely new to React and have just set everything up. However, when I try running the command "npm run start", I encountered the following error message: Module not found: Error: Can't resolve './reportWebVitals' ...

Do you think it's achievable to modify the color using CSS's order attribute?

When I look at the code in Firefox's inspector, I notice this : element { order:35; } Can a color be assigned to it? I am customizing my year outlook calendar and have set a particular day to display in a different color. But when I click on the mo ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

assigning a variable using jQuery

<script> function update(elem) { var ele=$(elem).siblings('label#test').html(); var a=document.getElementById('test'); var htm = '<input type="text" name="modal" id="modal" style="width:70%;" value="'+$(elem).siblings ...

Following deployment and page building in REACT JS, the pages fail to open

As a student still learning, I'm in need of assistance with a project. When I deploy the system and run the build, the initial page works fine but all redirects fail to work. If you'd like to view the page, it's available at: I'm seei ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

webdriverIO encountered an unhandled promise rejection, resulting in a NoSuchSessionError with the message "invalid session id

I am currently learning how to conduct UI testing using Jasmine and WebdriverIO in conjunction with NodeJS. Below is a snippet of my test code: const projectsPage = require('../../lib/pages/projects.page'); const by = require('selenium-we ...

React encountering difficulty showing images stored on a local path

Just starting out with React and I'm facing an issue while trying to show images from the src/images folder. Even after double-checking the path, the image still doesn't appear on the screen. Take a look at my image tag path and folder structure ...