Search code examples
reactjsreact-nativereact-native-text

Focus on TextInput from imported Component


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.


Solution

  • 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}