react-hook icon indicating copy to clipboard operation
react-hook copied to clipboard

How do I set `window` with `useMouse()` ?

Open s7tya opened this issue 2 years ago • 5 comments

Sorry for creating an issue that is not a bug report or feature request.

How do i set window as a target of useMouse() ? As I read the README, it looks like I can do that, but I couldn't find the way to do so.

https://github.com/jaredLunde/react-hook/blob/6c076415273124feffd5c1aae62152e1b199749f/packages/mouse-position/README.md?plain=1#L74

s7tya avatar Apr 19 '22 16:04 s7tya

you can but maybe the type is incorrect. would happily accept a PR that fixes it.

jaredLunde avatar Apr 19 '22 19:04 jaredLunde

I think the type is not the only thing to be fixed. Like we cannot use window obj in SSR?

( I’m a beginner so it might be wrong tho🙇)

s7tya avatar Apr 24 '22 23:04 s7tya

Using

  const mouse = useMouse(window as any);

fails. Typescript works fine, but there is a runtime stack trace.

Uncaught TypeError: element.getBoundingClientRect is not a function
    at _ref (index.js?64c7:27:1)
    at _ref2 (index.js?64c7:71:1)
    at updateReducer (react-dom.development.js?fc10:16664:1)
    at Object.useReducer (react-dom.development.js?fc10:17898:1)
    at Object.useReducer (react.development.js?443b:1626:1)
    at useMouse (index.js?64c7:142:1)

This is using the latest version of this library in the newest version of Chrome with recent react 18.

image

williamstein avatar Feb 22 '23 19:02 williamstein

My guess is that the solution to this issue is:

  • The place in the docs where it says that window is allowed as input should be removed, since window definitely does not work, since it doesn't have getBoundingClientRect, but this library assumes the input has that method.
  • Mention in the docs that if you need to listen for events on the entire window, use
const mouse = useMouse(document.body);

which I think does work as one would expect with the window. This is the case of an HTMLElement type input, which works fine.

williamstein avatar Feb 22 '23 19:02 williamstein

So the types are correct

jaredLunde avatar Feb 23 '23 03:02 jaredLunde