Skip to content

Commit

Permalink
Improve docs around using state instead of refs for the anchor element
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Sep 6, 2022
1 parent abb3e15 commit d1e4aed
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions packages/components/src/popover/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ Popover is a React component to render a floating content modal. It is similar i

## Usage

Render a Popover within the parent to which it should anchor:
Render a Popover within the parent to which it should anchor.

If a Popover is returned by your component, it will be shown. To hide the popover, simply omit it from your component's render value.

```jsx
import { Button, Popover } from '@wordpress/components';
Expand All @@ -25,7 +27,36 @@ const MyPopover = () => {
};
```

If a Popover is returned by your component, it will be shown. To hide the popover, simply omit it from your component's render value.
In order to pass an explicit anchor, you can use the `anchor` prop. When doing so, the anchor element should be stored in state rather than a plain ref to ensure reactive updating when it changes.

```jsx
import { Button, Popover } from '@wordpress/components';
import { useState } from '@wordpress/element';

const MyPopover = () => {
// Use internal state instead of a ref to make sure that the component
// re-renders when the anchor's ref updates.
const [ popoverAnchor, setPopoverAnchor ] = useState();
const [ isVisible, setIsVisible ] = useState( false );
const toggleVisible = () => {
setIsVisible( ( state ) => ! state );
};

return (
<p ref={ setPopoverAnchor }>Popover s anchor</p>
<Button variant="secondary" onClick={ toggleVisible }>
Toggle Popover!
</Button>
{ isVisible && (
<Popover
anchor={ popoverAnchor }
>
Popover is toggled!
</Popover>
) }
);
};
```

If you want Popover elements to render to a specific location on the page to allow style cascade to take effect, you must render a `Popover.Slot` further up the element tree:

Expand Down Expand Up @@ -155,6 +186,8 @@ Set this to hide the arrow which visually indicates what the popover is anchored

The element that should be used by the `Popover` as its anchor. It can either be an `Element` or, alternatively, a `VirtualElement` — ie. an object with the `getBoundingClientRect` function and the `ownerDocument` properties defined.

The element should be stored in state rather than a plain ref to ensure reactive updating when it changes.

- Type: `Element | VirtualElement`
- Required: No

Expand Down

0 comments on commit d1e4aed

Please sign in to comment.