Eliminable Chips feature in the Material UI Multiple Select component

The Material UI documentation showcases a multiple select example where the selected options are displayed using the Chip component and the renderValue prop on the Select. By default, clicking on the current value opens the list of available options.

I am attempting to modify this behavior so that each Chip displays an X button, allowing users to instantly remove an item from the selection by clicking the X, rather than opening the list of options.

Despite my efforts, I'm struggling to trigger the onDelete event of the Chip. Clicking the X still triggers the Select to open instead.

How can I ensure that the onDelete event takes precedence? Based on my understanding of event bubbling, it seems like the Chip should handle the event first.

View Code Sandbox Demo

Code:

const MultipleSelectDemo = () => {
  const [personName, setPersonName] = React.useState<string[]>(initialSelected);

  const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setPersonName(event.target.value as string[]);
  };
  
  // this never gets called
  const handleDelete = (e: React.MouseEvent, value: string) => {
    e.preventDefault();
    console.log("clicked delete");
    setPersonName((current) => _without(current, value));
  };

  return (
      <div>
        <FormControl>
          <InputLabel id="demo-mutiple-chip-checkbox-label">
            Chip + Check
          </InputLabel>
          <Select
            labelId="demo-mutiple-chip-checkbox-label"
            id="demo-mutiple-chip-checkbox"
            multiple
            value={personName}
            onChange={handleChange}
            onOpen={() => console.log("select opened")}
            IconComponent={KeyboardArrowDownIcon}
            renderValue={(selected) => (
              <div>
                {(selected as string[]).map((value) => (
                  <Chip
                    key={value}
                    label={value}
                    clickable
                    className={classes.chip}
                    onDelete={(e) => handleDelete(e, value)}
                    onClick={() => console.log("clicked chip")}
                  />
                ))}
              </div>
            )}
          >
            {names.map((name) => (
              <MenuItem key={name} value={name}>
                <Checkbox checked={personName.includes(name)} />
                <ListItemText primary={name} />
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </div>
  );
}

Answer ā„–1

The Select starts when the mouse-down event is triggered, not the click event.

To achieve the desired outcome, you should prevent the mouse-down event from propagating when it happens on the delete icon of the Chip:

<Chip
  key={value}
  label={value}
  clickable
  deleteIcon={
    <CancelIcon
      onMouseDown={(event) => event.stopPropagation()}
    />
  }
  className={classes.chip}
  onDelete={(e) => handleDelete(e, value)}
  onClick={() => console.log("clicked chip")}
/>

https://codesandbox.io/s/deletable-chip-in-multi-select-vk113?fontsize=14&hidenavigation=1&theme=dark

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

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

What is the method for indicating the data type in an XDR request?

Currently, I am successfully using XDR for cross domain resource sharing in IE. However, I am facing an issue with specifying the return dataType to receive JSON as responseText. Below is the snippet of my code: if (window.XDomainRequest && $.browser.m ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

I'm encountering an issue where the variable "user" cannot be found. This problem is arising while working with Firebase Auth alongside the most recent SDK version of Expo (SDK 42)

import { StyleSheet, Text, View } from "react-native"; import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import LoginScreen from " ...

Storing dynamic content on a server and retrieving it for future use

I'm working on a webpage that allows users to create elements dynamically and I want to save those elements to the server. When someone else visits the page, I want them to see those saved elements as well. I'm not too familiar with web programm ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

Does the CSV stream parser (PapaParse) cause rendering delays?

Currently, I am utilizing papa parse to fetch csv streams from my backend in order to visualize data. However, I have observed that while it is successfully invoking the callback for the data chunks, it is also causing rendering issues. I am attempting to ...

Modify MUI's ListItemText component by targeting a specific span to implement customized styles using the useStyle hook

It's quite perplexing that although this is a straightforward task in regular CSS, it must be accomplished through MUI's useStyles for some peculiar reason. Essentially, I possess a ListItem containing a ListItemText. It appears as follows: cons ...

What steps can I take to direct mobile visitors to the mobile-friendly version of my website?

Looking for a way to automatically redirect users on mobile devices from www.domain.com to the new mobile version at m.domain.com? ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

Exploring the world of end-to-end testing for playwright. How to handle oauth2 and email-passwordless authentication in your testing

As I delve into e2e testing with Playwright, I've encountered a challenge. The application I need to test can only be accessed through Github OAuth or email authentication links, managed by next-auth in a NextJS project. I'm unsure how to approa ...

What is the best way to reduce the spacing between bullets in a JoyUI List?

I have some lists on this page: However, I am looking to reduce the spacing between the bullets. Despite my attempts at adjusting the theme, I haven't been successful. Here is what I have tried so far: import { extendTheme } from "@mui/joy/style ...

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

Exploring the foundations of web development with html and stylus

If you have experience with the roots platform, you are familiar with its default stack including jade, stylus, and coffee script. The documentation provides some information on using HTML, CSS, and pure JavaScript instead of the compiled languages, but d ...

JavaScript popup menu with a redirect URL

I utilized Tinybox from this source for launching a popup webpage. I am hoping that when I click the links on the webpage, the popup will close itself and redirect to the link's URL. Here are my JavaScript and HTML codes: <script type="text/java ...

Utilizing Role-Based Access Control to Restrict Routes in React

Need help with setting up 2 routes for different types of users. I already have authentication in place, but unsure how to differentiate between the two. Any suggestions or links to relevant documentation would be greatly appreciated as I've been rese ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

"Exploring the versatility of using variables in jquery's .css

Iā€™m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...