Google News
logo
Popper.js - Interview Questions
What is Virtual Elements in Popper.js?
You can use a virtual element instead of a real DOM element as the reference. This allows you to position the popper relative to a virtual area defined by any coordinates you desire.
 
A common use case for this is making the popper follow the mouse cursor, where the cursor acts as a point reference.
 
A virtual element is a plain object:
type VirtualElement = {|
  getBoundingClientRect: () => ClientRect | DOMRect,
  contextElement?: Element,
|};
contextElement is an optional property that describes the DOM context of the virtual element. This is necessary if getBoundingClientRect is derived from a real DOM element, and that element is within a different scrolling container context to the popper element.

Usage : This will make the popper follow the mouse cursor as seen in the demo above:
function generateGetBoundingClientRect(x = 0, y = 0) {
  return () => ({
    width: 0,
    height: 0,
    top: y,
    right: x,
    bottom: y,
    left: x,
  });
}

const virtualElement = {
  getBoundingClientRect: generateGetBoundingClientRect(),
};

const instance = createPopper(virtualElement, popper);

document.addEventListener('mousemove', ({ clientX: x, clientY: y }) => {
  virtualElement.getBoundingClientRect = generateGetBoundingClientRect(x, y);
  instance.update();
});
Advertisement