Skip to content Skip to sidebar Skip to footer

How To Disable The Selection Of An Item When The First Letter Of The Option Is Pressed In The Select Component?

I'm using material UI Select component and I'm trying to build a filter inside to display only the items that match the input entered by the user. I build a minimal example of what

Solution 1:

The text focus navigation functionality is implemented in the onKeyDown of MenuList (I implemented it about 6 months ago). Stopping propagation of that event on the MenuItem (it would also work to stop propagation on the TextField) prevents the event from reaching MenuList.

import * asReactfrom"react";
import { render } from"react-dom";
importTextFieldfrom"@material-ui/core/TextField";
importSelectfrom"@material-ui/core/Select";
importMenuItemfrom"@material-ui/core/MenuItem";

import"./styles.css";

functionApp() {
  const [selectedOption, setSelectedOption] = React.useState("");
  const [filterExpression, setFilterExpression] = React.useState("");

  constonChangeSelection = (
    event: React.ChangeEvent<{ name?: string | undefined; value: unknown }>,
    child: React.ReactNode
  ) => {
    const value = event.target.value.toString();
    setSelectedOption(value);
  };

  constonChangeExpression = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const value = event.target.value.toString();
    console.log(`value:`, value);
    setFilterExpression(value);
  };

  conststopImmediatePropagation = (e: any) => {
    e.stopPropagation();
    e.preventDefault();
  };

  return (
    <divclassName="App"><SelectonChange={onChangeSelection}value={selectedOption}><MenuItemdensedividervalue={""}
          onClickCapture={stopImmediatePropagation}onKeyDown={e => e.stopPropagation()}
        >
          <TextFieldvalue={filterExpression}onChange={onChangeExpression} /></MenuItem><MenuItemdensekey={"One"} value={"One"}>
          One
        </MenuItem><MenuItemdensekey={"Two"} value={"Two"}>
          Two
        </MenuItem><MenuItemdensekey={"Three"} value={"Three"}>
          Three
        </MenuItem></Select></div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Edit Stop text focus navigation

Post a Comment for "How To Disable The Selection Of An Item When The First Letter Of The Option Is Pressed In The Select Component?"