How can I get the text / value of a textinput by its ref?

Viewed 5310
4 Answers

I couldn't solve the problem, apparently there is no way to get this property in pure React-Native.

So I started using the TextInput component of the react-native-paper package. This way the same code worked, I can get the text now with this excerpt:

console.log(refContainerStep1.current.state.value);

use useRef() instead of createRef();

const textInput = useRef(null);

<TextInput
   ref={textInput}
....../>

You can access the ref via refContainerStep1.current.

What you can then do is check the Prototype property to check which methods you can use.

I noticed there's a function called _getText which can be used to obtain a value.

An example of grabbing the value in an onPress:

const onPress = () => { 
  console.log(refContainerStep1.current.__proto__); // See available methods
  console.log(refContainerStep1.current._getText()); // Grab the value
}

Do it that way

  const onButtonClick = () => {
      console.log('get value from parent')
      console.log(ref1.current.props.value)
      console.log(ref2.current.props.value)
  };

Example in expo

Parent

import * as React from 'react';
import { Text, View, StyleSheet,TextInput } from 'react-native';
import Constants from 'expo-constants';

import MyTextInput from './components/AssetExample';

import { Card } from 'react-native-paper';

export default function App() {
  const ref1 = React.createRef();
  const ref2 = React.createRef();

  const onButtonClick = () => {
      console.log(ref1.current.props.value)
      console.log(ref2.current.props.value)
  };

  return (
    <View style={styles.container}>
      <Card>
      <button onClick={onButtonClick}>get value</button>
      <MyTextInput  label={'label 2'} secure={false}  ref={ref1} />
      <MyTextInput  label={'label 1'} secure={true}  ref={ref2} />
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

});

Child

import React, { useState, useEffect } from 'react';
import { TextInput as RnTextInput, StyleSheet, View, Text } from 'react-native';

const styles = StyleSheet.create({
  textInput: {
    padding: 10,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 50,
  },
  text: {
    marginLeft: 20,
    marginBottom: 10,
    fontSize: 20,
  },
});

const TextInput = React.forwardRef((props, ref) => {
  const [text, setText] = useState('');
  return (
    <View>
      {props.label && <Text style={styles.text}>{props.label}</Text>}
      <RnTextInput
        style={styles.textInput}
        value={text}
        onChange={(e) => {
          setText(e.target.value);
        }}
        secureTextEntry={props.secure}
        ref={ref}
      />
    </View>
  );
});

export default TextInput;
Related