Search code examples
reactjsreact-nativeviewmeasure

SafeAreaView measure function not working in react native


my problem is that I have to measure View using the basic measure function. However, if SafeArea uses that function, it will not work.

const headerRef = useRef(null);
...
  useEffect(() => {
    headerRef.current.measure( (ox, oy, width, height, px, py) => {
    set({
      ox: ox,
      oy: oy,
      width: width,
      height: height,
      px: px,
      py: py,
    });
  };);
  }, []);
...
<SafeAreaView style={styles.safeArea} ref={headerRef}>

Error is

TypeError : Cannot read property 'measure' of undefined

How can you solve this problem?

Is there anyone who has the same problem as me?


Solution

  • I solved this problem using just View, not SafeAreaView. SafeAreaView doesn't seem to apply this part.

    const headerRef = useRef(null);
    ...
      useEffect(() => {
        headerRef.current.measure(getViewSize); 
      }, []);
    ...
    const getViewSize = (ox, oy, width, height, px, py) => {
        set({
          ox: ox,
          oy: oy,
          width: width,
          height: height,
          px: px,
          py: py,
        });
      };
    ...
    <View style={styles.safeArea} ref={headerRef}>
    

    Edit use onLayout

    • sample
    <View style={styles.safeArea} onLayout={({
                        nativeEvent: {
                            layout: { width, height, x, y }
                        }
                    }) => console.log(width, height, x, y)}>
    

    ref : https://reactnative.dev/docs/layoutevent