reactjsdrop-down-menufloatingpopper.jsreact-popper

floating-ui react-dom-interactions how to set floating element width same as reference width


In my react app I am trying to build a dropdown menu with floating-ui/react-dom-interactions (formerly knowns as react-popper). Here is a codesandbox link to a demo of my component. Here is a output of the current state of the app.

Dropdown output

I want to set the floating element width same as reference element. I have tried to follow this approach from documentation but didn't get the desired output. How can I set the floating element width same as reference element.


Solution

  • And the last solution with size key , as defined in the package

    const { x, y, reference, floating, strategy, context } = useFloating({
        placement,
        open,
        middleware: [
          offset(4),
          size({
            apply({ rects, elements }) {
              Object.assign(elements.floating.style, {
                width: `${rects.reference.width}px`
              });
            }
          }),
          flip(),
          shift({ padding: 5 })
        ],
        onOpenChange: setOpen,
        whileElementsMounted: autoUpdate
      });
    

    Check sandbox - https://codesandbox.io/s/angry-marco-4yhuer?file=/src/SecondaryCategoryItems.jsx