Dropdown Menu loses position in DOM

22 views Asked by At

I have a dropdown menu with a custom toggle. I created my custom toggle as follows:

const CustomToggle = forwardRef<HTMLAnchorElement, CustomProps>( ({ children, onClick }, ref) => { return ( <a href="" ref={ref} onClick={(e) => { e.preventDefault(); setTest((prev) => !prev); onClick(e); }} > Custom toggle </a> ); } );

and my dropdown component is:

` <Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components" />

  <Dropdown.Menu>
    <Dropdown.Item eventKey="1">Red</Dropdown.Item>
    <Dropdown.Item eventKey="2">Blue</Dropdown.Item>
    <Dropdown.Item eventKey="3" active>
      Orange
    </Dropdown.Item>
    <Dropdown.Item eventKey="1">Red-Orange</Dropdown.Item>
  </Dropdown.Menu>
</Dropdown>`

Full sandbox here: https://codesandbox.io/s/ecstatic-frost-ztry6z?file=/src/customToggle.tsx

My menu opens and closes as expected on the first 2 clicks, but on the third the menu translates up to the top left corner of the screen. You can literally see:

transform: translage3d(-118.5px, -55px, 0px)

get applied to the menu div. The real kicker is it only behaves like this when there is a state change within the component, which I included in the CustomToggle onClick above as:

setTest((prev) => !prev);

If I remove the state change the menu continues to render in the correct place, but in my real life example I need it. Can anyone explain why this is happening?

I tried this example straight from the react-bootstrap examples and added the state change and expected the menu to render in the correct place every time, but it did not. The menu renders correctly the first open and close click but then it gets translated up to the upper left corner of the screen every time after. This only happens when there is a local state change included. I need the local state change and I need the menu to render in the correct place every time.

0

There are 0 answers