Ionic 5 + React: positioning a popover relative to the clicked element

In the documentation, the requirement to have an Ionic 5 popover present itself beside a clicked element that activates the popover, you need to pass the mouse event to it.

To do so, you must assign the event prop of the IonPopover with the event value.

However, since React also nullifies all event properties due to Event Pooling and Ionic is looking for the event target to help position the IonPopover, you will first have to persist the event.

Extending the documentation‘s example to enable relative positioning of the popover in React, note the differences:

  1. showPopoverEvent local state defaults to null, and will hold an event object.
  2. isOpen still expects a boolean, and is true if showPopoverEvent is not empty.
  3. IonButton onClick must call persist on the event, and we set the local state to store the event.
  4. Finally, the event prop on IonPopover is set to the event stored in the local state.
import React, { useState } from 'react';
import { IonPopover, IonButton } from '@ionic/react';

export const PopoverExample: React.FC = () => {
  const [showPopoverEvent, setShowPopoverEvent] = useState(null);

  return (
    <>
      <IonPopover
        isOpen={!!showPopoverEvent}
        onDidDismiss={() => setShowPopoverEvent(null)}
        event={showPopoverEvent}
      >
        <p>This is popover content</p>
      </IonPopover>
      <IonButton onClick={(e) => { e.persist(); setShowPopoverEvent(e); }}>
        Show Popover
      </IonButton>
    </>
  );
};
0 thoughts on “Ionic 5 + React: positioning a popover relative to the clicked element”

Leave a Reply

%d bloggers like this: