Issue
I am creating a custom component, the script is written in TypeScript using React's Hooks
My component will be using some of my typescript type and mix it with TextInput type (so i can access TextInput props)
This is my custom component sample code
import { Animated, Platform, TextInput, TextInputProps, View } from 'react-native'
type PropsType = TextInputProps & { //Or should I using TextInput instead of TextInputProps?
myCustomProp?: string
}
const CustomTextField = (props: PropsType) => {
useEffect(() => {
return () => {
if(props.onSubmitEditing != undefined) {
props.onSubmitEditing()
}
}
}, [])
return (
<View
style = {{
}}
/>
)
}
export default CustomTextField
Then I import it on my screen and display it like this
<CustomTextField
placeholder = 'Password'
ref = {passwordInput}
secureTextEntry
/>
and this is my ref variable
const passwordInput = useRef<typeof CustomTextField>(null)
but the typescript give me error when ref to the component
Solution
From docs, You may not use the ref attribute on function components because they don’t have instances.
But in recent times, functional components have become popular because of hooks and everything, React has introduced forwardRef.
so your child component code should be of
export default React.forwardRef((props: CustomProps, ref) => {
// All other existing code
});
in the parent component,
const passwordInput = useRef<CustomTextField>(null)
<CustomTextField
placeholder='Password'
ref={passwordInput}
secureTextEntry
/>
Answered By - senthil balaji

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.