user14587589
user14587589

Reputation: 459

React native useRef is giving me undefined

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?

Upvotes: 0

Views: 721

Answers (2)

calii23
calii23

Reputation: 88

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.

Upvotes: 1

Waleed Nasir
Waleed Nasir

Reputation: 607

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>
    </>
  );
}

Upvotes: 1

Related Questions