Search code examples
reactjstypescriptionic-frameworkpopoverionic-react

How to dynamically position a IonPopover to appear from a button?


I'm trying to position a popover to appear underneath a button when that button is clicked. An example of this is on the Ion docs page. enter image description here

However the code for this is not supplied in React, only in Angular.

Currently my code looks like this

...
<IonButtons slot="end">
                        <IonButton onClick={() => setShowPopover(true)} expand="block">
                            <IonIcon icon={more}/>
                        </IonButton>
                    </IonButtons>
                    <IonPopover
                        isOpen={showPopover}
                        backdropDismiss={true}
                        onDidDismiss={() => setShowPopover(false)}>
                        <IonItem>Popover Item</IonItem>
                    </IonPopover>
...

The popover is toggled by the button above it. When the button is pressed the popover appears in the middle of the page, not over the button. How do I change this so the popover is shown attached to the button? (Like the image)

Thanks


Solution

  • Inspired by the answer of Thomas but unable to make his code work the following did the trick for me:

    const [showPopover, setShowPopover] = useState<{open: boolean, event: Event | undefined}>({
      open: false,
      event: undefined,
    });
    
    <IonPopover
        isOpen={showPopover.open}
        event={showPopover.event}
        onDidDismiss={e => setShowPopover({open: false, event: undefined})}
    >
       <p>This is popover content</p>
    </IonPopover>
    <IonButton onClick={(e) => setShowPopover({open: true, event: e.nativeEvent})}>Click</IonButton>