How can I correctly set the typing for this ref?
I'm getting a typescript warning when using .contains
in buttonRef.current?.contains()
.
As far as I know, .contains()
only exists on the web. Besides this, the code works on the web.
The code is essentially a listener that determines what was clicked.
The full example: Expo Snack
Relevant part of code:
// How to properly define the ref? const buttonRef = React.useRef(null); const orangeRef = React.useRef(null); React.useEffect(() => { if (Platform.OS !== 'web') return; const handler = (e: MouseEvent) => { const target = e.target; // Want to avoid the ts warning here saying contains doesn't exist on current if (buttonRef.current?.contains(target)) { setMsg('you clicked the button'); } else if (orangeRef.current?.contains(target)) { setMsg('you clicked the orange box'); } else { setMsg('you clicked the background'); } }; window.addEventListener('mousedown', handler); return () => window.removeEventListener('mousedown', handler); }, []);