javascriptreact-nativereact-native-component

How to use Ref in a component that is forwarding its ref in React Native


I have a react native custom input component and I'm successfully forwarding its ref to a parent component. Now, I also want to refer to the input in the child itself, How do I do this??

//my imports here

//my text field component
export const MyTextField = React.forwardRef((props, ref) => {

   const [inputValue, setValue] = useState('');

   const clearInput = () => {
      setValue("");
      //I want to get the input by ref here and apply "clear()" method on it
   }


   return (
      <View>
         <TextInput
            /*
             How can i also use this ref to refer to this textinput in The "clearInput" function above
             */
            ref={ref}
            value={inputValue}
            onChangeText={(value) => setValue(value)}
            {...props}
         />
         <IconButton
            icon="close-circle"
            onPress={clearInput}
         />
      </View>
   );
});


Solution

  • This article by Travis Waith-Mair shows what you want to do with details: https://non-traditional.dev/how-to-use-the-forwarded-ref-in-react-1fb108f4e6af

    Also there's an npm package of it: https://www.npmjs.com/package/@bedrock-layout/use-forwarded-ref


    Here is a snack with examples: https://snack.expo.io/@truetiem/use-forwardedref

    If you want to implement it into your code:

    // Copy-Pasted the "useForwardedRef" from the linked article by "Travis Waith-Mair"
    const useForwardedRef = (ref) =>{
       const innerRef = useRef(null);
    
       useEffect(() => {
         if (!ref) return;
         if (typeof ref === 'function') {
           ref(innerRef.current);
         } else {
           ref.current = innerRef.current;
         }
       });
     
       return innerRef;
    }
    
    export const MyTextField = React.forwardRef((props, ref) => {
       // passing the ref to useForwardedRef hook
       const forwardedRef = useForwardedRef(ref);
       const [inputValue, setValue] = useState('');
    
       const clearInput = () => {
          setValue("");
          
          // You can access the ref safely with forwardedRef
          forwardedRef.current?.clean();
       }
    
    
       return (
          <View>
             <TextInput
                // Passing the forwardedRef here
                ref={forwardedRef}
                value={inputValue}
                onChangeText={(value) => setValue(value)}
                {...props}
             />
             <IconButton
                icon="close-circle"
                onPress={clearInput}
             />
          </View>
       );
    });