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.
Asked: 2023-05-31 00:18:36 +0000
Seen: 1 times
Last updated: May 31 '23