0

In React Native, I am using Custom Component of TextInput with forwardRef, input.current.focus() and input.current.clear() is working fine, but input.current.value is always undefined.

I have google around a lot, and tried many things, but issue still persist. Below is my code.

Here is custom component code:

const AuthInput = (
  {label = 'Label', isSecure = false, error = null, onChangeText},
  textRef,
) => {
  console.log('AUTHINPUT called');
  return (
    <View style={styles.container}>
      <Text style={styles.label}>{label}</Text>
      <TextInput
        ref={textRef}
        style={styles.input}
        secureTextEntry={isSecure}
        onChangeText={onChangeText}
      />
      {error && <Text style={styles.error}>{error}</Text>}
    </View>
  );
};

const forwaredInput = React.forwardRef(AuthInput);
export default forwaredInput;

I am calling that component and passing 'ref' like below (Parent Component):

const emailFieldRef = useRef(null);

  const onLogin = () => {
    console.log(emailFieldRef.current.value);
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.form}>
        <AuthInput
          ref={emailFieldRef}
          label={'Email'}
          error={emailError}
          // eslint-disable-next-line no-shadow
          onChangeText={email => {
            // setEmail(email);
          }}
        />
        <StretchedButton title={'Sign in'} onPress={() => onLogin()} />
      </View>
    </SafeAreaView>
  );
};
  • Can you avoid using refs ? If yes you should, it will speed up your application and the logic will be easier. – lmasneri Jun 21 '22 at 13:30
  • `ref.current` doesn't have `value` property. But I can't understand, if you want to access the input value, it's your `email` that's returned from `onChangeText={email => {` this function – Leri Gogsadze Jun 21 '22 at 13:52
  • @LeriGogsadze, I want to practice forwardRef, so I was just playing around this scenario. It is working for other people But on React js. Could not find this scenario for React Native. "input.current.value" has issue while using forwardRef, otherwise in simple useRef, it is working fine. – Muhammad Haroon Iqbal Jun 21 '22 at 14:52
  • @Imasneri, We should use refs while working with input fields to avoid unnecessary Renderings, this is what I have heard. – Muhammad Haroon Iqbal Jun 21 '22 at 14:56
  • @MuhammadHaroonIqbal React `input` and React Native `TextInput` components are different – Leri Gogsadze Jun 21 '22 at 16:39

0 Answers0