Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable "Select By Typing" in Material UI Menu Component

I'm trying to make a pop-up menu that has a couple different filters (buttons, selects, and text fields). I'm using the Material UI Menu component, but have run into an issue when trying to use the text fields. Because the Menu component is acting like a <Select />, when I type something in the text fields, it tries to select different MenuItems instead of staying focused on the text box.

So using the example found in the sandbox below, users wouldn't be able to type anything in the "search for a different food" textbox if it started with an "A", "B", or "C". If you wanted to type in "apricots", the menu would change focus from the textbox to the "Apples" MenuItem.

I don't see any props for this in the Menu API, so I'm curious to know if there is any work arounds, or even a different component that is more suited for this.

Thanks!

Here's a codesandbox: https://codesandbox.io/s/wizardly-mccarthy-zy2b7

import { useState } from "react";
import "./styles.css";
import { Button, Menu, MenuItem, TextField } from "@material-ui/core";

export default function App() {
  const [menu, setMenu] = useState(null);
  const [text, setText] = useState("");

  return (
    <div className="App">
      <Button variant="outlined" onClick={(e) => setMenu(e.currentTarget)}>
        Filters
      </Button>

      <Menu
        anchorEl={menu}
        open={Boolean(menu)}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left"
        }}
        onClose={() => setMenu(null)}
      >
        <MenuItem>Apples</MenuItem>
        <MenuItem>Bananas</MenuItem>
        <MenuItem>Carrots</MenuItem>
        <MenuItem>
          <TextField
            value={text}
            onChange={(e) => setText(e.target.value)}
            variant={"outlined"}
            label={"search a different food..."}
          />
        </MenuItem>
      </Menu>
    </div>
  );
}
like image 487
AwoeDace Avatar asked Dec 06 '25 13:12

AwoeDace


1 Answers

Use e.stopPropagation() in the onKeyDown event for the MenuItem containing the TextField. This will prevent the key down event from propagating to the Menu component.

    <MenuItem onKeyDown={(e) => e.stopPropagation()}>
        <TextField
            value={text}
            onChange={(e) => setText(e.target.value)}
            variant={"outlined"}
            label={"search a different food..."}
        />
    </MenuItem>

Reference: How to disable the selection of an item when the first letter of the option is pressed in the Select component?

like image 97
jpotts17 Avatar answered Dec 09 '25 01:12

jpotts17



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!