mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
We need to handle ref cleanups in a way that is compatible with React 18 and 19. Forking these into -pages (18) and -app (19). Combining them into a single app lead to a different behavior with regards to preload.
57 lines
1.3 KiB
JavaScript
57 lines
1.3 KiB
JavaScript
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
|
import Link from 'next/link'
|
|
|
|
const useClickAway = (ref, onClickAway) => {
|
|
useEffect(() => {
|
|
const handler = (event) => {
|
|
const el = ref.current
|
|
|
|
// when menu is open and clicked inside menu, A is expected to be false
|
|
// when menu is open and clicked outside menu, A is expected to be true
|
|
console.log('A', el && !el.contains(event.target))
|
|
|
|
el && !el.contains(event.target) && onClickAway(event)
|
|
}
|
|
|
|
let timeoutID = setTimeout(() => {
|
|
timeoutID = null
|
|
document.addEventListener('click', handler)
|
|
}, 0)
|
|
|
|
return () => {
|
|
if (timeoutID != null) {
|
|
clearTimeout(timeoutID)
|
|
}
|
|
document.removeEventListener('click', handler)
|
|
}
|
|
}, [onClickAway, ref])
|
|
}
|
|
|
|
export default function App() {
|
|
const [open, setOpen] = useState(false)
|
|
|
|
const menuRef = useRef(null)
|
|
|
|
const onClickAway = useCallback(() => {
|
|
console.log('click away, open', open)
|
|
if (open) {
|
|
setOpen(false)
|
|
}
|
|
}, [open])
|
|
|
|
useClickAway(menuRef, onClickAway)
|
|
|
|
return (
|
|
<div>
|
|
<div id="click-me" onClick={() => setOpen(true)}>
|
|
Open Menu
|
|
</div>
|
|
{open && (
|
|
<div ref={menuRef} id="the-menu">
|
|
<Link href="/">some link</Link>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|