Permitting the user to remove an option from the antd select widget

I have integrated the antd select component in my React application and I am looking to add a delete option for users.

For more details, please refer to the image below:https://i.sstatic.net/ZP4PP.png

This is how I attempted to implement it:

 {tasks.map((task) => {
    return (
      <Option value={task.value}>
        <span>{task.label}</span>
        <span style={{ float: "right" }}>
          <DeleteOutlined />
        </span>
      </Option>
    );
 })}

However, this approach resulted in the following output: https://i.sstatic.net/wVrHD.png

The issue I'm encountering is that I don't want the delete icon to appear on the selected value after a user makes a selection.

NOTE: Clicking on the delete icon should trigger the deletion of the entry from the database.

Answer №1

Take a look at this example that demonstrates the use of optionLabelProp within the <Select/> component

https://i.sstatic.net/vUl4c.png

<Select optionLabelProp="label">  /* Include optionLabelProp here */
  {items.map((task) => {
    return (
      <Option value={task.value} label={task.label}> /* Add label here */
        {task.label}
      </Option>
    );
  })}
</Select>

Example

App.jsx

import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { DeleteOutlined } from "@ant-design/icons";
import { Select } from "antd";

const App = () => {
  const { Option } = Select;
  const [items, setItems] = useState([
    {
      id: 1,
      value: "james",
      label: "James"
    },
    {
      id: 2,
      value: "lucy",
      label: "Lucy"
    },
    {
      id: 3,
      value: "lisa",
      label: "Lisa"
    },
    {
      id: 4,
      value: "peter",
      label: "Peter"
    }
  ]);

  const handleChange = (value) => {
    console.log(`selected ${value}`);
  };

  const deleteOption = (value) => {
    setItems(
      items.filter((item) => {
        return item.value !== value;
      })
    );
    console.log("deleted", value);
  };

  return (
    <>
      <Select
        defaultValue="lucy"
        optionLabelProp="label"
        style={{
          width: 170
        }}
        onChange={handleChange}
      >
        {items !== undefined &&
          items.map((task) => {
            return (
              <Option key={task.id} value={task.value} label={task.label}>
                <span>{task.label}</span>
                <span style={{ float: "right" }}>
                  <DeleteOutlined
                    onClick={(e) => {
                      e.stopPropagation();  /* Include e.stopPropagation() */
                      deleteOption(task.value);
                    }}
                  />
                </span>
              </Option>
            );
          })}
      </Select>
    </>
  );
};
export default App;

Output:

https://i.sstatic.net/05rja.gif

https://i.sstatic.net/5EZ2w.png

Update:

Add e.stopPropagation() to fix selection issue while deleting the option

<DeleteOutlined
   onClick={(e) => {
   e.stopPropagation(); /* Include e.stopPropagation() */
   deleteOption(task.value);
   }}
/>

Hope this explanation is beneficial! Appreciate your time :)

Answer №2

The Ant Design documentation states that the menuItemSelectedIcon property can be utilized.

For instance:

<Select menuItemSelectedIcon={<DeleteOutlined />} />

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

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Having trouble getting the sorting/search function to work with a click event to display content. It seems to only work with a single item - possibly an issue with the

Creating a function that involves multiple boxes with a search function. The search function is working for the most part, but when clicking on a result, certain content should display. function filterFunction() { var input, filter, ul, li, a, i; ...

Having trouble fetching an image file in Node.js after submitting it from React

Trying to send an image file from react to nodejs has been a challenge. I have implemented the SetImage function to set the selected image file to the 'myimage' state variable, and then used Axios to post the images to the '/blog/posts' ...

The perplexity surrounding the concept of immutability in Redux

While studying Redux, I encountered some confusion regarding how the reducer updates the state. Consider this code snippet: const initialState = { counter: 0 }; const counterReducer = (state = initialState, action) => { if(action.type==="INCREASE" ...

Interactive Sideways Navigation Bar

showcases a sleek horizontal scrolling menu on mobile devices. I aim to replicate this functionality for a website I'm redesigning that features extensive navigation elements. Key Features: Left and right scroll button options Centered list item op ...

To overcome the 401 (Unauthorized) error on specific requests, how can one bypass it when trying to access http://localhost:3000/user/auth

I am encountering a 401 (Unauthorized) error when trying to access certain requests that do not require user authentication. For instance, in an eCommerce store, all visitors should be able to view products without logging in, but sellers need to authentic ...

Using Reactjs to bind onClick event to a list component generated dynamically

If I have a render function that resembles the following: render() { var user_rows = [] this.state.user_list.forEach((user, index) => { user_rows.push( <tr key={user}> <td><div className="bt ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

Ways to conceal the TippyJS tooltip so it doesn't show up on video embeds

My website has tooltips enabled, but I am looking to hide the tooltip pop-ups that appear specifically over youtube video embeds. Upon inspecting the webpage, I found the code snippet below that is associated with youtube videos: <div data-tippy-root id ...

What is the best way to transfer image files into a specific folder?

I am currently in the process of developing a ReactJS web application. My goal is to upload images to a specific folder and then store the file name in the database for future use. Everything seems to be working smoothly up to this point, but I am facing ...

What is the best way to pass environment variables in Vercel for applications outside of Next.js?

After deploying a standard React application to Vercel, I am interested in setting up an API_BASE_URL environment variable with different values for the development, preview, and production environments. Normally, I would utilize the dotenv npm package al ...

Arrows on the button are unresponsive and there seems to be an incorrect number of

I've been working on a project by combining various examples I found online. I'm puzzled as to why it's displaying all the buttons at once instead of just one per page, and why the number of visible buttons decreases by one with each right c ...

Changing the value of an input field based on a user's input

Looking to automatically format any input in an input field as currency: <input type="text" value="0,00 EUR" onChange={(e) => { e.target.value = convertToCurrency(e.target.value) }} /> const convertToCu ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Reasons for aligning inline elements with input boxes

I am facing a challenge with aligning a series of inline elements, each containing an input text box, within a single row. The number and labels of these input boxes can vary as they are dynamically loaded via AJAX. The width of the div housing these inli ...

Change the color of the text to be the opposite of the background

I'm facing a challenge while creating a website for my friend. The background of the site is a moving image, and I want the font color of the main title to be the opposite of it on each frame. While I know this may require CSS, I am unsure of how to ...

Create a list of items that are enclosed within a parent element

My menu is generated from a php query and the output is as follows: #ultra-menu { width: 92%; background-color: rgba(255, 255, 255, 0.90); position: absolute; left: 0px; right: 0px; margin: auto; border-radius: 35px; max-height: 300px; ...

The information in the table quickly appears in its raw format before being formatted and enhanced by jquery DataTables

I have encountered an issue where table data loads briefly and unformatted before jquery DataTables kicks in. After doing some research, I found that many suggest hiding the table using CSS and then showing it using jQuery with initComplete. However, des ...

Using JQuery's .mouseover and .mouseout methods to modify font colors on a webpage

Hi there, I'm new to JQuery and trying to experiment with some basic functionalities. I have a simple navigation menu created using an unordered list, and I want to change the font color of the currently hovered list item using JQuery. However, I&apos ...