I've looked at many of the docs and examples but I still can't seem to quite understand how to use forwardRef
with a functional component with TypeScript in React Native. Below is an example where I create a MyCustomComponent
with a custom function that I try to call from the parent by creating a ref. However, since the ref is incorrectly defined and null
, I obviously get an error message telling me that the function doesn't exist. Please help me understand how to properly use forwardRef
in React Native. Thanks in advance!
interface MyCustomComponentProps { title: string}const MyCustomComponent: React.FunctionComponent<MyCustomComponentProps> = React.forwardRef((props, ref) => { const coolAlert = () => { Alert.alert('Hey!', 'This was called from MyCustomComponent') } return (<View><Text>{props.title}</Text></View> )})export default function App () { const MyCustomComponentRef = useRef() return (<SafeAreaView><MyCustomComponent ref={MyCustomComponentRef} title='Hello World' /><TouchableOpacity onPress={() => { MyCustomComponentRef.coolAlert() }}><Text>Click Me</Text></TouchableOpacity></SafeAreaView> )}