When I click on Dropdown.Item
, Dropdown.Menu
hides. I want to prevent this, i.e. leave Dropdown.Menu
open after a click, and close it only if there was a click outside of Dropdown
at all. I've found similar questions, but there were in original bootstrap using jQuery. How to implement this in react-bootstrap? Thanks
////
<Dropdown.Menu>
<Dropdown.Item>- Pending</Dropdown.Item>
<Dropdown.Item>- Completed</Dropdown.Item>
<Dropdown.Item>- Cancelled</Dropdown.Item>
</Dropdown.Menu>
////
When I click on Dropdown.Item
, Dropdown.Menu
hides. I want to prevent this, i.e. leave Dropdown.Menu
open after a click, and close it only if there was a click outside of Dropdown
at all. I've found similar questions, but there were in original bootstrap using jQuery. How to implement this in react-bootstrap? Thanks
////
<Dropdown.Menu>
<Dropdown.Item>- Pending</Dropdown.Item>
<Dropdown.Item>- Completed</Dropdown.Item>
<Dropdown.Item>- Cancelled</Dropdown.Item>
</Dropdown.Menu>
////
Share
Improve this question
asked Aug 7, 2020 at 22:57
GorgeousPureeGorgeousPuree
3911 gold badge3 silver badges11 bronze badges
1
- I just went with react-select and set closeMenuOnSelect={false} – GorgeousPuree Commented Aug 17, 2020 at 15:49
4 Answers
Reset to default 7Add autoClose="inside"
to the Dropdown component.
By default, the dropdown menu is closed when selecting a menu item or clicking outside of the dropdown menu. This behavior can be changed by using the autoClose property.
By default, autoClose is set to the default value true and behaves like expected. By choosing false, the dropdown menu can only be toggled by clicking on the dropdown button. the inside makes the dropdown disappear only by choosing a menu item and the outside closes the dropdown menu only by clicking outside.
https://react-bootstrap.github.io/docs/components/dropdowns
Try this:
const [isShown, setIsShown] = useState(false);
const onToggleHandler = (isOpen, e, metadata) => {
if (metadata.source != 'select') {
setIsOpen(isOpen);
}
}
<Dropdown
show={isShown}
onToggle={(isOpen, e, metadata) => onToggleHandler(isOpen, e, metadata)}
>
*onSelect method can be used normally
You can make use of show prop of Dropdown. Using this you can manually hide and show the dropdown.
So what i did is i added dropdown props state variable to the Dropdown element and then using onToggle function i hide and show dropdown on particular conditions.
<Dropdown {...this.state.dropdownProps} onToggle={(isOpen, event) => this.onToggleFunction(isOpen, event)} />
For functional components, simply create the state:
const [ show, setShow ] = useState(false);
Then write your dropdown component like this:
<Dropdown show = {show}>
<Dropdown.Toggle onClick = {() => setShow(!show)}>Toggle Trigger.</Dropdown.Toggle>
</Dropdown>