Focus on TextInput from imported Component

852 views Asked by At

I have a TextInput in my Component (FirstComponent). I can call the focus on it from the component by calling the this.refs. I am also importing and calling another Component (SecondComponent) which also needs to focus on the TextInput on a button click.

My First Component:

Import SecondComponent from './SecondComponent';

<View>
    <TouchableOpacity
        onPress={()=>this.refs.MyBox.focus()}  
    >
        <Text>Open</Text>
    </TouchableOpacity>


    <SecondComponent />


    <TextInput
      ref='MyBox'
      style={{width: '100%', borderColor: 'gray', borderWidth: 1}}
    />

</View>

The SecondComponent too has a TouchableOpacity to call the focus on the TextInput:

<View>
    <TouchableOpacity
        onPress={()=>this.refs.MyBox.focus()}  
    >
        <Text>Open</Text>
    </TouchableOpacity>
</View>

The SecondComponent is rendered fine but cannot call the focus on the TextInput since it's not in the SecondComponent. How do I resolve this?

Thanks.

2

There are 2 answers

1
Kraylog On BEST ANSWER

You can either pass the reference to the TextInput directly:

<SecondComponent textInput={this.refs.MyBox} />

And then in SecondComponent call this.props.textInput.focus(), or you can pass in the function that does the focusing and invoke it within the second component:

focusOnTextInput = () => this.refs.MyBox.focus();

<View>
    <TouchableOpacity
        onPress={this.focusOnTextInput}>
    ...
    <SecondComponent onPress={this.focusOnTextInput}/>

And then in SecondComponent:

onPress={this.props.onPress}
0
Artem Mirchenko On

Refs of component cannot call from another component. In your case you need to setup method in parent component which takes a component need to focus, and focused it. And then you pass this method as props to child components.

focusMethod(component) {
 component.focus()
}

this.props.focusMethod(this.refs.MyBox);