Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add warning when using <Popover.Button /> multiple times #2007

Merged
merged 2 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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