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

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

Closed
saintwinkle opened this issue May 15, 2024 · 2 comments
Closed

Comments

@saintwinkle
Copy link

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

@childrentime
Copy link
Owner

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
}

@saintwinkle
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants