diff --git a/src/index.tsx b/src/index.tsx index 198b4f5..cb39532 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,11 +1,9 @@ import * as React from 'react' -import { ViewProps, View, StyleSheet, Platform } from 'react-native' +import { ViewProps, View, StyleSheet } from 'react-native' import { PropsWithChildren, ReactNode, useState, - useRef, - useLayoutEffect, } from 'react' import Svg, { Color, Path } from 'react-native-svg' import { getSvgPath } from 'figma-squircle' @@ -144,34 +142,27 @@ function Rect({ children, ...rest }: RectProps) { const [rect, setRect] = useState<{ width: number; height: number } | null>( null ) - const ref = useRef(null) - useLayoutEffect(() => { - if (!isSyncLayoutAccessAvailable()) { - throw new Error("This library requires React Native's new architecture.") - } - - // TODO: Maybe use `getBoundingClientRect` instead when it's stable https://gist.github.com/lunaleaps/148756563999c83220887757f2e549a3#file-tooltip-uselayouteffect-js-L77 - // From my testing, `measureInWindow` is still faster than `unstable_getBoundingClientRect` - ref.current?.measureInWindow((_x, _y, width, height) => { - setRect({ width, height }) - }) - }, []) + const handleLayout = React.useCallback( + (e: { nativeEvent: { layout: { width: number; height: number } } }) => { + const { width, height } = e.nativeEvent.layout + setRect((prev) => { + if (prev && prev.width === width && prev.height === height) { + return prev + } + return { width, height } + }) + }, + [] + ) return ( - + {rect ? children(rect) : null} ) } -function isSyncLayoutAccessAvailable() { - if (Platform.OS === 'web') { - return true - } - - return (globalThis as any).RN$Bridgeless === true -} export { SquircleView, getSvgPath } export type { SquircleParams, SquircleViewProps }