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

Time:07-31

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 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.

CodePudding user response:

As I see you have a grid the grid-cols-4 for categories , it means each of one width is 25% , I can suggest one solution without going deeper into package possibilities , Just add one class like

<div className={"bg-gray-700 py-2 text-white px-3 w-1/5 flex flex-col"}
  {...getFloatingProps({
  ref: floating,
  className: "Tooltip",
  style: {
    position: strategy,
    ref: floating,
    top: y ?? 0,
    left: x ?? 0,
  }
 })}
>

define styles in the index.css like

.Tooltip {
  background: #222;
  color: white;
  font-weight: bold;
  padding: 5px;
  border-radius: 4px;
  font-size: 90%;
  pointer-events: none;
  width: 25%;
}

CodePudding user response:

One other solution with paddings , As I check in the main parent you have add px-8 , it means , 2 em from the start and end , you can pass grid and padding to the SecondaryCategoryItems component and calculate minWidth there like minWidth: ("100" / grid ) - (p / 4) "%"

Sandbox example - https://codesandbox.io/s/cold-monad-vqm7ch?file=/src/SecondaryCategoryItems.jsx:1304-1340

CodePudding user response:

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

  • Related