Home > Mobile >  Create a dropdown that will appear after clicking on chip component that is within TextField
Create a dropdown that will appear after clicking on chip component that is within TextField

Time:08-03

I am having trouble trying to implement a customized dropdown that does not seem to be a built in feature in Material UI. I am using Material UI for all these components btw. So I have a TextField with a Chip for the End Adornment.

The expected behavior is that if the user were to click on the chip, there should be a dropdown that pops up under the TextField where the user can select the type of vehicle. However, I don't think there is a built in Material UI way to do this. Any suggestions? Any suggestions would be appreciated. Thanks!

enter image description here

CodePudding user response:

You can implement it like this:

https://codesandbox.io/s/hungry-golick-kdoylz?file=/src/App.js

import { useState } from "react";
import { TextField, Chip, InputAdornment, Menu, MenuItem } from "@mui/material";
import KeyboardArrowDown from "@mui/icons-material/KeyboardArrowDown";

export default function App() {
  const [selectedItem, setSelectedItem] = useState("Jeep");
  return (
    <TextField
      label="With normal TextField"
      InputProps={{
        endAdornment: (
          <InputAdornment position="end">
            <ChipDropDown
              items={["Jeep", "Volvo", "Ferrari"]}
              selectedItem={selectedItem}
              onChanged={setSelectedItem}
            />
          </InputAdornment>
        )
      }}
      variant="filled"
    />
  );
}

const ChipDropDown = ({ items, selectedItem, onChanged }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const handleClick = (item) => {
    onChanged(item);
    setAnchorEl(null);
  };
  return (
    <div>
      <Chip
        label={selectedItem}
        onClick={(e) => setAnchorEl(e.currentTarget)}
        onDelete={(e) => e}
        deleteIcon={<KeyboardArrowDown />}
      />
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={(e) => setAnchorEl(null)}
      >
        {items.map((item) => (
          <MenuItem key={item} onClick={(e) => handleClick(item)}>
            {item}
          </MenuItem>
        ))}
      </Menu>
    </div>
  );
};
  • Related