reactuse
reactuse copied to clipboard
useEventListener won't fire on elements that are not visible at first
Reproduction
Hi, just found another issue:
function Demo() {
const [visible, setVisible] = useState(false)
const buttonRef = useRef(null)
const onClick = () => {
console.log('button clicked!') // not working...
}
useEventListener('click', onClick, buttonRef)
useTimeoutFn(() => {
setVisible(true)
}, 1000)
return visible ? <button ref={buttonRef}>Click me</button> : null
}
If the button is visible at first, then the event can be bound successfully.
All hooks using useEventListener might be affected in this situation, at least useScroll is not working. Perhaps we should test them all.
Sorry to bother ;-) 🥰
This is a classic issue in React, as initially, the element bound with the ref does not exist.
May be you can try it to
function Demo() {
const [visible, setVisible] = useState(false)
const [buttonRef, setButtonRef] = useState(null)
const onClick = () => {
console.log('button clicked!') // not working...
}
useEventListener('click', onClick, buttonRef)
useTimeoutFn(() => {
setVisible(true)
}, 1000)
return visible ? <button ref={setButtonRef}>Click me</button> : null
}
This is a classic issue in React, as initially, the element bound with the ref does not exist.
May be you can try it to
function Demo() { const [visible, setVisible] = useState(false) const [buttonRef, setButtonRef] = useState(null) const onClick = () => { console.log('button clicked!') // not working... } useEventListener('click', onClick, buttonRef) useTimeoutFn(() => { setVisible(true) }, 1000) return visible ? <button ref={setButtonRef}>Click me</button> : null }
Thanks, it works!