Home > Enterprise >  How to avoid dropdown menu hiding while click on checkbox inside the dropdown list items?
How to avoid dropdown menu hiding while click on checkbox inside the dropdown list items?

Time:05-19

Need to avoid the dropdown menu hiding while clicking on 'checkbox' inside the dropdown list items. dropdown menu should hide when click outside of dropdown & dropdown toggle button area , also selected items value should load in dropdown toggle text area. please help, I am using react-bootstrap dropdown

 <Dropdown className="dropdown-groove">
        <Dropdown.Toggle variant="outline-secondary " id="dropdown-basic">
          Select...
          <label className="dropdown-label">Dropdown label</label>
        </Dropdown.Toggle>

        <Dropdown.Menu>
          <Dropdown.Item href="#/action-1">
            {" "}
            <Form.Check
              className="checkbox-groove"
              inline
              label="Unselected"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
          <Dropdown.Item href="#/action-2">List Item 2</Dropdown.Item>
          <Dropdown.Item href="#/action-3">List Item 3</Dropdown.Item>
          <Dropdown.Item href="#/action-4">List Item 4</Dropdown.Item>
          <Dropdown.Item href="#/action-5">List Item 5</Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>

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

CodePudding user response:

Add onClick={(e) => e.stopPropagation()} in <Form.Check>...</Form.Check>. e.stopPropagation() in tag will help this tag prevent onClick event from parent.

Code here: https://codesandbox.io/s/dropdown-with-checkbox-forked-88h9m6?file=/src/App.js

import "./styles.scss";
import "bootstrap/dist/css/bootstrap.min.css";
import { Dropdown, Form } from "react-bootstrap";
export default function App() {
  return (
    <div className="App">
      <Dropdown className="dropdown-groove">
        <Dropdown.Toggle variant="outline-secondary " id="dropdown-basic">
          Select...
          <label className="dropdown-label">Dropdown label</label>
        </Dropdown.Toggle>

        <Dropdown.Menu>
          <Dropdown.Item href="#/action-1">
            {" "}
            <Form.Check
              onClick={(e) => e.stopPropagation()} //<=== Add here
              className="checkbox-groove"
              inline
              label="Unselected"
              name="group1"
              type="checkbox"
            />{" "}
          </Dropdown.Item>
          <Dropdown.Item href="#/action-2">List Item 2</Dropdown.Item>
          <Dropdown.Item href="#/action-3">List Item 3</Dropdown.Item>
          <Dropdown.Item href="#/action-4">List Item 4</Dropdown.Item>
          <Dropdown.Item href="#/action-5">List Item 5</Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>
    </div>
  );
}
  • Related