Prevent closing after click on Dropdown.Item in React-bootstrap

Viewed 4853

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>
////
4 Answers

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)} />

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

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>

Add 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/components/dropdowns/

Related