Unverified Commit ffa66ff5 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

fix: error overlay not closing when backdrop clicked (#83981)

The ref object wasn't passed to the hook; instead, ref.current (the
value) was passed. This caused `useOnClickOutside` to be noop on initial
render when ref.current was null, and only worked later because the
component re-rendered with a different value. The fix ensures the hook
always has access to the current DOM element whenever the effect runs.

### Before


https://github.com/user-attachments/assets/baa7ea6c-9506-4f14-8950-b4e7e7abbe61

### After


https://github.com/user-attachments/assets/18c3c569-ca30-41c3-ae92-f2d3e8fcee4c
parent 4160af22
......@@ -37,8 +37,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({
)
useOnClickOutside(
// eslint-disable-next-line react-hooks/refs -- TODO
dialogRef.current,
dialogRef,
CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE,
(e) => {
e.preventDefault()
......
import * as React from 'react'
export function useOnClickOutside(
el: Node | null,
el: Node | React.RefObject<Node | null> | null,
cssSelectorsToExclude: string[],
handler: ((e: MouseEvent | TouchEvent) => void) | undefined
) {
React.useEffect(() => {
if (el == null || handler == null) {
// Support both direct nodes and ref objects
const element = el && 'current' in el ? el.current : el
if (element == null || handler == null) {
return
}
const listener = (e: MouseEvent | TouchEvent) => {
// Do nothing if clicking ref's element or descendent elements
if (!el || el.contains(e.target as Element)) {
if (!element || element.contains(e.target as Element)) {
return
}
......@@ -28,7 +30,7 @@ export function useOnClickOutside(
handler(e)
}
const root = el.getRootNode()
const root = element.getRootNode()
root.addEventListener('mouseup', listener as EventListener)
root.addEventListener('touchend', listener as EventListener, {
passive: false,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment