0

I have been working on ReactJS but totally new to React Native. I am trying to use useRef on TextInput but it did not work.

const Playground = () =>{

  const inputName = useRef();

  const addName = e => {
    Alert.alert(inputName.current.value);  
  }

  return (
      <SafeAreaView>    
            <TextInput ref={inputName} placeholder="name"></TextInput>
            <Button title="add" onPress={addName}></Button>          
      </SafeAreaView>
  );
}

export default Playground;

With the code I use in ReactJS above, it always returns me empty string when pressing the button to addName. I also tried to useEffect as below but got the same results.

  useEffect(() => {
    if(!inputName.current) return;

    Alert.alert(inputName.current.value);

  }, [inputName.current])

Tried to do some search but I could not find the answer. Can I use useRef in React Native as the same as ReactJS?

seanbun
  • 624
  • 3
  • 10
  • 24
  • 1
    I think your problem is similar to https://stackoverflow.com/questions/40324660/how-to-get-the-value-of-a-textinput-in-an-onpress-handler. I suggest you control your value via state instead of getting it from the ref, but if you prefer there is this _lastNativeText property you can use. – glneto Nov 04 '19 at 01:29
  • Thanks gIneto. I am more curious to know if I should not use `useRef` in react native. – seanbun Nov 04 '19 at 01:40
  • We have `useRef` in production with `react-native`, it works as expected for us. – azundo Nov 04 '19 at 06:24

2 Answers2

0

You can try this:

inputName.current._root.props.value
Dino
  • 6,207
  • 8
  • 28
  • 62
miladino43
  • 11
  • 1
  • 3
0

I believe React Native strongly encourages using state instead of ref. You can get away with useState in this particular case.

See also Direct Manipulation

Pavel Chuchuva
  • 21,289
  • 9
  • 93
  • 110