Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the End Adornment.

The desired outcome is for the user to be able to click on the chip and trigger a dropdown menu under the TextField where they can choose a vehicle type. Unfortunately, it seems like there is no direct way to achieve this using Material UI components. Are there any suggestions or alternatives that could help me accomplish this task? Your input would be greatly appreciated. Thank you!

https://i.stack.imgur.com/81Gk5.png

Answer №1

To implement this functionality, follow the code below:

Link to code implementation

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>
  );
};

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

What are some techniques for concealing a CSS transition beneath another element in both directions?

Witness the magic in action! By clicking on the black box below, a larger black box will gracefully emerge from beneath the sidebar. While it may not be as clear in jsfiddle, rest assured that this effect is more pronounced in browsers. Thanks to some clev ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Sorting method in Ext JS 6.2.0 using mode

Seeking clarification on the sort([field],[direction],[mode]) method in Ext JS 6.2.0. Can someone explain the distinction between append, prepend, replace, and multi as mentioned in the documentation available at this link? I am unable to find a clear expl ...

Manipulating files with the Play framework

I am looking to upload a file from the client side and process it on the server side without having to reload the entire webpage. I am currently working with Scala in Play framework 2.X, utilizing separate HTML and JavaScript scripts. The file types I am w ...

Exploring the creation of a dynamic graph with d3.js

I'm new to d3 and attempting to create a graph layout. var w = 1000; var h = 500; var dataset = { nodes: [{ name: 'Alice' }, { name: 'David' ...

Experiencing a lack of information in express?

Whenever I attempt to send a POST request (using fetch) with the body containing the state of the application, I receive an empty object on the server side. What am I doing wrong here? I should be receiving the object with the properties name, username, an ...

I am attempting to access data through an ajax function, but it is not functioning correctly

When working with asp.net webform, I encountered an issue while trying to call data using an ajax call. Although a similar function on another page works without errors, on this particular page, I am facing an error. The error I am getting is pageCountInt ...

Encountering issues with reading undefined properties while working with react-chartjs-2 and chart js

Having trouble with react chartjs errors? Visit the link for more details https://i.stack.imgur.com/lI2EP.png The versions I'm using are ^3.5.0 for chart.js and ^4.0.1 for react-chartjs-2 Tried downgrading to version 2 but it didn't solve the ...

Access the data attribute of a button element in AngularJS

Utilizing Angularjs for managing pagination loop button id=remove_imslide, I am attempting to retrieve the value of data-img_id from the button to display in an alert message using a Jquery function on button click, but I am encountering issues. This is h ...

Styling CSS Based on Input from Child Siblings

Is it possible to customize an adjacent element based on a valid input from a child element? Let's say we have the following HTML structure: <div id="source"> <input type="text"> </div> <div id="target"> </div> Below ...

"Using jQuery to trigger a click function on elements with the same

Whenever I click the comment link all of the divs are opening but i need that particular only to be opened. HTML: <div> <a href="#" class="ck">comment</a> <div class="cmt"> <input type="text" class="txt"/> ...

Experimenting with React component functionality using Enzyme and Jest

Currently, I am in the process of testing a component that follows the Container/Presentational pattern. To achieve 100% coverage, I need to test the handleChange() function which contains a setState() method. The challenge lies in the fact that I am only ...

Populating a Dual ListBox with JSON data

I'm currently using a dual listbox control from and am attempting to populate it with information retrieved from a JSON request. Initially, I populated the Duallistbox using a VB sub like this: Public Shared Sub GenerateDropDownListAndValues(dt As ...

Trigger the D3 component to re-render in React after a state change occurs in the parent component

My React project consists of two components written in TypeScript. The first component contains menus, and I am using conditional rendering to display different content based on user selection. <Menu.Item name="graph" active={activeItem ...

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

Is there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...