Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created September 20, 2024 11:37
Show Gist options
  • Save everdimension/085fb89fb6a692e4d6b5170fb6f9b036 to your computer and use it in GitHub Desktop.
Save everdimension/085fb89fb6a692e4d6b5170fb6f9b036 to your computer and use it in GitHub Desktop.
Draft for a button+dropdown using popover api + anchor api + react
import { useId } from 'react';
function Example() {
const id = useId();
return (
<div style={{ position: 'relative' }}>
<button
// @ts-ignore TODO: Update to react@v18.3 (currently tested on ^18.2.0)
popovertarget={id}
popovertargetaction="toggle"
style={{ paddingInline: 8, ['anchorName' as string]: '--popover-1' }}
onClick={() => {
// optionally do something else besides opening the dropdown
}}
onKeyDown={(event) => {
const popoverEl = event.currentTarget
.nextElementSibling as HTMLDivElement;
if (event.key === 'Escape' && popoverEl.matches(':popover-open')) {
// Prevent closing extension popup, close only popover
event.preventDefault();
popoverEl.hidePopover();
}
}}
>
button text
</button>
<div
id={id}
// @ts-ignore TODO: Update to react@v18.3
popover="auto"
style={{
position: 'absolute',
['positionAnchor' as string]: '--popover-1',
margin: 0,
top: 'anchor(bottom)',
left: 'anchor(start)',
border: 'none',
backgroundColor: 'transparent',
}}
onKeyDown={(event) => {
if (event.key === 'Escape') {
// Prevent closing extension popup, close only popover
event.preventDefault();
event.currentTarget.hidePopover();
}
}}
>
<div>{/* dropdown menu content */}</div>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment