Skip to content

Commit

Permalink
Add warning when using <Popover.Button /> multiple times (#2007)
Browse files Browse the repository at this point in the history
* add warning when using `<Popover.Button />` multiple times

* update changelog
  • Loading branch information
RobinMalfait committed Nov 10, 2022
1 parent c0f0d43 commit f0dd25f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- Reset form-like components when the parent `<form>` resets ([#2004](https://github.com/tailwindlabs/headlessui/pull/2004))
- Add warning when using `<Popover.Button />` multiple times ([#2007](https://github.com/tailwindlabs/headlessui/pull/2007))

## [1.7.4] - 2022-11-03

Expand Down
23 changes: 22 additions & 1 deletion packages/@headlessui-react/src/components/popover/popover.tsx
Expand Up @@ -55,6 +55,8 @@ enum PopoverStates {
interface StateDefinition {
popoverState: PopoverStates

buttons: HTMLElement[]

button: HTMLElement | null
buttonId: string
panel: HTMLElement | null
Expand Down Expand Up @@ -201,6 +203,7 @@ let PopoverRoot = forwardRefWithAs(function Popover<

let reducerBag = useReducer(stateReducer, {
popoverState: PopoverStates.Closed,
buttons: [],
button: null,
buttonId,
panel: null,
Expand Down Expand Up @@ -387,10 +390,28 @@ let Button = forwardRefWithAs(function Button<TTag extends ElementType = typeof
let panelContext = usePopoverPanelContext()
let isWithinPanel = panelContext === null ? false : panelContext === state.panelId

let id = useId()
let buttonRef = useSyncRefs(
internalButtonRef,
ref,
isWithinPanel ? null : (button) => button && dispatch({ type: ActionTypes.SetButton, button })
isWithinPanel
? null
: (button) => {
if (button) {
state.buttons.push(id)
} else {
let idx = state.buttons.indexOf(id)
if (idx !== -1) state.buttons.splice(idx, 1)
}

if (state.buttons.length > 1) {
console.warn(
'You are already using a <Popover.Button /> but only 1 <Popover.Button /> is supported.'
)
}

button && dispatch({ type: ActionTypes.SetButton, button })
}
)
let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref)
let ownerDocument = useOwnerDocument(internalButtonRef)
Expand Down

0 comments on commit f0dd25f

Please sign in to comment.