React Native - TextInput focus while onClick Text Label won't work

I just want to make textinput focus easier for more user-friendly application. I try to do when user miss click textinput and click text instead it should focus to textinput.

So I added ref to text as

  <Text ref={"textref"}

and on TextInput

 <TextInput onPress={_onPress => { this.refs.textref.focus() }} 

It worked for 1 word label texts but It didn't worked for long texts. What can I do?

Also it says refs is deprecated is there better way to do it? I find this way shortest and effective but sadly it is deprecated.

Edit: I fixed it.

<Text onPress={() => {this.inputText.focus()}} 
<TextInput ref={input => { this.inputText= input}}   

worked for me.

2 answers

  • answered 2021-06-10 11:23 BloodyMonkey

    First, you're trying to focus a Text, but you can focus only TextInput

    Then, i suggest you to init your ref in the constructor

    constructor(props) {
        super(props)
        
        ...
    
        this.textInputref = React.createRef()
    }
    

    And

    <Text onPress={() => this.textInputref.current.focus()}>hello world</Text>
    
    <TextInput ref={this.textInputref} /> 
    

  • answered 2021-06-10 11:37 Birender Pathania

    You could use is simply like this:

    <Text onPress={_onPress => { this.refs.textref.focus() }}> Testing </Text>
    <TextInput ref={"textref"}/>