Ask Your Question
1

On React-Bootstrap's Dropdown.Item component, when a custom JSX element is clicked, why doesn't the dropdown close?

asked 2023-05-31 00:18:36 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-31 00:23:01 +0000

ladyg gravatar image

The Dropdown.Item component is designed to handle click events on its own content only. If a custom JSX element is used inside the Dropdown.Item component, the event listener will not be attached to that element, and it will not close the dropdown when clicked.

To close the dropdown when a custom JSX element is clicked, you can add an onClick handler to the custom element that calls the Dropdown's hide method. For example:

import { Dropdown } from 'react-bootstrap';

function CustomItem() {
  const dropdownRef = useRef(null);

  const handleCloseDropdown = () => {
    if (dropdownRef.current) {
      dropdownRef.current.hide();
    }
  };

  return (
    <div onClick={handleCloseDropdown}>
      My custom item
    </div>
  );
}

function Example() {
  return (
    <Dropdown>
      <Dropdown.Toggle variant="success" id="dropdown-basic">
        Dropdown Button
      </Dropdown.Toggle>

      <Dropdown.Menu>
        <Dropdown.Item as={CustomItem} ref={dropdownRef} />
      </Dropdown.Menu>
    </Dropdown>
  );
}

In this example, we create a ref to the Dropdown component, and pass it to the custom element using the ref prop. When the custom element is clicked, the handleCloseDropdown handler is called, which uses the ref to call the Dropdown's hide method, closing the dropdown.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-31 00:18:36 +0000

Seen: 1 times

Last updated: May 31 '23