Home > Enterprise >  How to get multiple selected list items values in dropdown toggle?
How to get multiple selected list items values in dropdown toggle?

Time:05-20

Need to get all selected values inside dropdown toggle with out removing previously loaded value, Please help

const [selectedItem, setSelectedItem] = useState("Select...");
<Dropdown className="dropdown-groove">
        <Dropdown.Toggle variant="outline-secondary " id="dropdown-basic">
          {selectedItem}
          <label className="dropdown-label">Dropdown label</label>
        </Dropdown.Toggle>

        <Dropdown.Menu>
          <Dropdown.Item href="#/action-1">
            {" "}
            <Form.Check
              onClick={(e) => {
                setSelectedItem("List A");
                e.stopPropagation();
              }}
              className="checkbox-groove"
              inline
              label="List Item 1"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
          <Dropdown.Item href="#/action-2">
            {" "}
            <Form.Check
              onClick={(e) => {
                setSelectedItem("List b");
                e.stopPropagation();
              }}
              className="checkbox-groove"
              inline
              label="List Item 2"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
</Dropdown.Menu>
</Dropdown>

https://codesandbox.io/s/dropdown-with-checkboxs-nvw3hz

CodePudding user response:

You could declare a function after setState in line 6

function toggleCheckbox(addItem) {
    if (selectedItem.indexOf(addItem) < 0) {
      setSelectedItem(`${selectedItem} ${addItem}`);
    } else {
      setSelectedItem(selectedItem.replace(addItem, ""));
    }
  } 

and replace setSelectedItem("List A"); with toggleCheckbox("List A"); then, List b & c is same way to replace.

codebox

  • Related