Search code examples
reactjsreact-bootstrap

Autoclose='outside' doesn't work with multiple menu in react-bootstrap


I have a dropdown with 2 possibles menus that can reach each others by clicking on some dropdown items. By adding autoClose='outside' I fixed the problem of untimely closing when clicking somewhere in the dropdown main menu. But since I have another menu, once it's showed, the first time I open it, the autoClose doesn't really work, instead, it's as if it was never set, close the whole dropdown, and when I reopen it, go in the secondary menu for the second, this 'bug' doesn't occur again on this menu, but occurs when I go back in the first one etc..

I suspect it's because autoClose only works on the current selected menu, in the example below it works with the main menu and does not in the secondary menu first then, as described above, when I reopen the dropdown it shows directly the secondary menu, works, and once I go back in the main menu, it doesn't.

This is basically the code I'm running.

import {Dropdown} from 'react-bootstrap';
import {useState} from 'react';

const Mydropdown = (props) => {

    const [menu,setMenu] = useState('main');

    return(
    <>
        <Dropdown autoClose='outside'>
        {
          menu=="main"
          &&
          (
            <>
              <Dropdown.Menu>
                <Dropdown.Item onClick={()=>setMenu("secondary")}>
                    Secondary menu
                </Dropdown.Item>
              </Dropdown.Menu>
            </>
          )
        }
        {
          menu=="secondary"
          &&
          (
            <>
              <Dropdown.Menu>
                <Dropdown.Item onClick={()=>setMenu("main")}>
                    Secondary menu
                </Dropdown.Item>
              </Dropdown.Menu>
            </>
          )
        }
      </Dropdown>
    </>
  );

}

Solution

  • I'm not sure I'm following your requirements 100%, but this version should allow a single dropdown to optionally toggle contents (without auto-closing):

    const Mydropdown = (props) => {
      const [menu, setMenu] = useState("main");
    
      return (
    <Dropdown autoClose="outside">
      <Dropdown.Toggle variant="primary">Dropdown Test</Dropdown.Toggle>
    
      <Dropdown.Menu>
        <Dropdown.Item href="#">Menu Item</Dropdown.Item>
        <Dropdown.Item href="#">Menu Item</Dropdown.Item>
        <Dropdown.Item href="#">Menu Item</Dropdown.Item>        
        {menu == "main" && (
          <Dropdown.Item onClick={() => setMenu("secondary")}>
            Secondary menu
          </Dropdown.Item>
        )}
        {menu == "secondary" && (
          <Dropdown.Item onClick={() => setMenu("main")}>
            Main menu
          </Dropdown.Item>
        )}
      </Dropdown.Menu>
    </Dropdown>
      );
    };
    

    Working example available here: https://codepen.io/ablewhite/pen/BawdVpg