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

How to use forwardRef with FunctionComponent in React Native using TypeScript

$
0
0

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>    )}

Viewing all articles
Browse latest Browse all 6215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>