Search code examples
react-nativenative-base

React Native - How to use a ref to set focus to an input when clicking on text


Here's what I'm doing:

export default class myComponent extends Component {
    render() {
        return (
            <View>
                 <Text onPress={() => {this.input.focus()}}>Click Me</Text>
                 <Input ref={input => { this.input = input}}/>
            </View>
        )
    }
}

I am using native-base components... not sure if that is affecting this. When I press the Text component, I get an error stating: _this2.input.focus is not a function. (In '_this2.input.focus()', '_this2.input.focus' is undefined)


Solution

  • I don't use native-base, but at normal it should be like this:

    import * as React from 'react';
    import { Text, View, StyleSheet, TextInput, Dimensions } from 'react-native';
    import { Constants } from 'expo';
    
    const { width, height } = Dimensions.get('window');
    
    export default class App extends React.Component {
      render() {
        return (
          <View style={styles.container}>
            <Text onPress={() => {this.input.focus()}}>Click Me</Text>
            <TextInput style={styles.input} ref={input => { this.input = input}}/>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#ecf0f1',
      },
      input: {
        backgroundColor: '#bbb',
        width: width - 40,
        height: 40,
        paddingHorizontal: 10,
        paddingVertical: 5,
      }
    });
    

    You can see the snacks here: https://snack.expo.io/@gasparteixeira/inputfocus