react-nativenative-base

How can I close a Popover programatically with native base?


I am using Native Base Popover.

scenario
As a user,
I can press on the list,
So that I can select a fruit

enter image description here

My problem is I don't understand how to close the <Popover /> from the outside of the component.

Here is my organization

<Formik>
  <Popover>
    <FlatList>
      <Pressable onPress={() => handlePress(item.id)} /> //Banaba
      <Pressable onPress={() => handlePress(item.id)} /> //Potato
      <Pressable onPress={() => handlePress(item.id)} /> //Ananas


Solution

  • NativeBase offers a useDisclose() hook for handling opening/closing of modals and other popup windows.

    That hook provides an isOpen state (as @mainak's answer mentions) as well as onOpen() and onClose() functions to manipulate that state. You can pass these helpers as arguments as-needed into the props of the same name within the Popover component to handle open/close state.

    Optionally, you can in addition pass true or false into useDisclose() to override the starting value of isOpen (defaults to false).

    Here is an example below for reference.

    import React from "react";
    import { Popover, useDisclose } from "native-base";
    
    function MyComponent() {
      const { isOpen, onClose, onOpen } = useDisclose()
    
      return (
        <>
          <Button onPress={onOpen}>Open the Popover</Button>
          <Popover isOpen={isOpen} onClose={onClose}>
            <Popover.Content>
              <Popover.Arrow />
              <Popover.CloseButton />
              <Popover.Header>My Popover Title</Popover.Header>
              <Popover.Body>You can place the content of your popover inside the body.</Popover.Body>
              <Popover.Footer>
                <Button onPress={onClose} variant="ghost">Cancel</Button>
              </Popover.Footer>
            </Popover.Content>
          </Popover>
        </>
      )
    }