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?

4
  • Does focus() even return something? Its just an action without any result (other than focussing the element). Could you explain what you want to do? Commented Jan 5, 2021 at 11:40
  • Try with this answer on How can I use ref in TextField question. Is it working for you? Commented Jan 5, 2021 at 11:41
  • Current returns a huge object Commented Jan 5, 2021 at 11:41
  • I am trying to get the value from textInput, I thought using focus would solve it Commented Jan 5, 2021 at 11:45

2 Answers 2

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> </> ); } 
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I am trying to get the value of TextInput with it
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.