Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete.

For reference, attached is an image showcasing the initial appearance of the autocomplete menu: autocomplete menu

Highlighted below is the problematic code snippet:

import "./styles.css";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import * as React from "react";
import Button from "@mui/material/Button";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";

const options = [
  { key: "1", value: "Option One" },
  { key: "2", value: "Option Two" }
];

function BasicMenu({ option }) {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
  };

  return (
    <div>
      <Button
        color="success"
        variant="contained"
        id={`basic-button-${option.key}`}
        aria-controls={open ? `basic-menu-${option.key}` : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
      >
        open {option.value} menu
      </Button>
      <Menu
        id={`basic-menu-${option.key`}
        anchorEl={anchorEl}
        open={open}
        MenuListProps={{
          "aria-labelledby": `basic-button-${option.key`
        }}
      >
        <MenuItem>Do with {option.value}</MenuItem>
      </Menu>
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Autocomplete
        onClose={(e, reason) => {
          console.log(reason);
        }}
        getOptionLabel={({ value }) => value}
        renderOption={(props, value) => (
          <li {...props}>
            {value.value}
            <BasicMenu option={value} />
          </li>
        )}
        disablePortal
        id="combo-box-demo"
        options={options}
        renderInput={(params) => <TextField {...params} label="Option" />}
      />
    </div>
  );
}

Tried using event.stopPropagation(), along with assigning unique IDs to menus and buttons for potential resolution. The issue detected in the onClose function points out to blur.

Desired functionality involves maintaining the autocomplete open upon clicking the green button. Selecting an option within the dropdown should close normally. Closing upon clicking outside the autocomplete area should also remain unaffected.

Answer №1

For an easy fix, consider including the disableCloseOnSelect prop in your AutoComplete component. You can get more information about this feature here: https://mui.com/material-ui/api/autocomplete

<Autocomplete
    onClose={(e, reason) => {
      console.log(reason);
    }}
    getOptionLabel={({ value }) => value}
    renderOption={(props, value) => (
      <li {...props}>
        {value.value}
        <BasicMenu option={value} />
      </li>
    )}
    disablePortal
    disableCloseOnSelect
    id="combo-box-demo"
    options={options}
    renderInput={(params) => <TextField {...params} label="Option" />}
 />

If that solution doesn't solve the issue, you have the option to manually control the open prop. Simply use a useState hook and set it to true or false based on when you want the popper to close or open. This way, you can implement your own custom open/close logic.

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

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Tips for ensuring a div stays centered while resizing the window

When I resize the window, the div tab on the right side of the screen moves to the bottom right. How can I make it stay in the middle regardless of screen size? I've tried using margin-left:auto and margin-right:auto but it didn't work. Changing ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...

Using VueMultiselect with Vue 3: A guide for beginners

I'm currently experimenting with the vue multiselect component, but when I include it in the template, I am encountering a series of warnings and errors. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

New update: Adjusting the chart by using the slider to modify the date values on the x-axis

Update: I have made changes to the question, the issue with values not appearing on the x-axis has been resolved. Now, as the slider is moved, the data on the graph remains constant and I can see changing x values. I am currently working on incorporating ...

Unable to apply the responsive Tailwind class to the Material-UI component

How can I add top margin to my button only on mobile devices? import { Button } from '@mui/material'; <Button type="submit" variant="contained" color="primary" className="w-full md:w-auto sm:mt-4& ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

What is the process for including a class on a div element?

I have written a code that displays a series of images in a sequence. Once the last image appears, I want to switch the class from .d-none to .d-block on the div Can this be achieved? onload = function startAnimation() { var frames = document.getE ...

Issue with unit tests failing to properly update states after calling setState within a callback function

Exploring a basic modal component has led me to a scenario where upon clicking a button to open it, a request is triggered with two callback functions (success and error). The success callback aims to modify three states: function successGetData(data) { ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...

Is it necessary to have both Express and express-generator in my toolbox?

Recently delving into the world of node.js and stumbled upon express; While browsing the npm repository site https://www.npmjs.com/package/express, I noticed that the installation process is clearly stated as: $ npm install express However, further down ...

Can Enzyme snapshots be utilized with React fragments?

Are React fragments compatible with Enzyme's snapshots? Currently, it appears that fragments from React 16+ are being displayed as Symbols in enzyme's shallow() method, leading to a conversion error: "TypeError: Cannot convert a Symbol value to a ...

Utilizing the spread operator in Typescript interfaces: best practices

I have a react component that includes the spread operator operating on ...other and passed down to lower levels of the component. interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: st ...

The Javascript slider fails to function properly when utilizing AJAX to load the page

I have encountered an issue while trying to open an HTML page using ajax when a button is clicked. The HTML page that I am opening contains a JavaScript slider that functions properly when opened individually, but stops working if opened through my index. ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...