Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Typescript: React Native Web useRef on Pressable - How to define the type

$
0
0

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);  }, []);

Viewing all articles
Browse latest Browse all 6287

Trending Articles