0

I am trying to use useRef hook this way. I want to get the value of textInput with it

  let tagsRef = useRef('');



 <TextInput
                ref={tagsRef}
                style={styles.textInputStyle}
                placeholder={'Add tags to subscribe to them'}
                placeholderTextColor={'lightgray'}
              />
            </View>

I am using react-native version:0.63.3

When I

 console.log(----tag', tagsRef.current.focus());

It gives me undefined

Any suggestions please?

user14587589
  • 449
  • 3
  • 19

2 Answers2

1

Check this its Officially RN Documentation

https://reactjs.org/docs/hooks-reference.html#useref

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Waleed Nasir
  • 579
  • 5
  • 9
1

It is depending on where do you use the ref. The ref is only filled after the first rendering. You can use it for instance in an event handler on the element.

Another point: You might see that the focus method does not return anything. So when you see an undefined in your console, it is properly related to that problem.

But without further context of your code and your problem, it is hard to give a more detailed answer.

calii23
  • 88
  • 2
  • 4
  • I am trying to get the value of TextInput with it – user14587589 Jan 05 '21 at 11:44
  • In that case, it seems that controlled input are more suited for your application. You can read details about that topic [here in the RN Documentation](https://reactnative.dev/docs/handling-text-input). – calii23 Jan 05 '21 at 11:57