Home > Software design >  Get the childrens of an element in react native using useRef
Get the childrens of an element in react native using useRef

Time:05-04

I am trying to understand how to use useRef in React Native and get the children of a View element, but I couldn't figure out to achieve it.

I am trying to use the .focus method in the TextInput component on press on the TouchableOpacity

Declaration:

const input = useRef(null);

TextInputComponent:

<View ref={input}>
  <Tex>Email</Text>
  <TextInput placeholder=""/>
</View>

Element:

 <TouchableOpacity onPress={() => {}}>
    <TextInputComponent />
 </TouchableOpacity>

i tried input.current.children, but it returns undefined.

CodePudding user response:

This is a working example of how to achieve what you want using on a basic expo init project on TypeScript:

App.tsx

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, TextInput, TouchableOpacity} from "react-native";
import { useRef, forwardRef} from "react";

const TextInputComponent = forwardRef<TextInput>((props, ref) => {
  return (
    <View>
      <Text>Email</Text>
      <TextInput ref={ref} placeholder="Some placeholder" />
    </View>
  );
});

export default function App() {
  const input = useRef<TextInput>(null)

  return (
    <View style={styles.container}>
      <Text>Open up App.tsx to start working on your app!</Text>
      <StatusBar style="auto" />
      <TouchableOpacity onPress={() => {
input.current?.focus();
      }}>
        <TextInputComponent ref={input} />
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

In this case it is more practical to use a forwardRef so you don't have to loop through the children of the View component to pass a ref from the component (App in this case) that is using TextInputComponent.

  • Related