reactuse icon indicating copy to clipboard operation
reactuse copied to clipboard

useEventListener won't fire on elements that are not visible at first

Open saintwinkle opened this issue 1 year ago • 1 comments

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 ;-) 🥰

saintwinkle avatar May 15 '24 07:05 saintwinkle

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
}

childrentime avatar May 15 '24 12:05 childrentime

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!

saintwinkle avatar May 19 '24 02:05 saintwinkle