Almost_Ashleigh
Almost_Ashleigh

Reputation: 534

React Native Focus Text Input On Next Press

Note: I am aware there are a lot of similiar questions and I have tried to implement answers on them but have not been successful.

In my React Native app, I have a form that accepts a finite amount of custom text input components. I am trying to find a solution for moving to the next input when a user presses the return button.

I’ve tried a few packages but none seemed to work super well with Android. I’ve also tried using refs but can’t seem to have luck (note the form is a functional component). It keeps returning undefined when I try to access it inside the the float label component.

Custom component:

<FloatLabelTextInput
          value={billingFirstName}
          onChangeText={newText => setBillingFirstName(newText)}
          autoCorrect={false}
          style={globalStyles.textInput}
          label="Billing First Name"
        />



The float label text input component renders a text input (with material based floating labels).


import React, { Component } from 'react';
import {
  Alert,
  Button,
  View,
  TextInput,
  Animated,
  Image,
  TouchableOpacity,
} from 'react-native';
import colors from '../utils/colors';

export default class FloatLabelTextInput extends Component<Props> {
  static defaultProps = {
    editable: true,
    showHelp: false,
  };

  state = {
    isFocused: false,
  };



  componentDidUpdate() {
    Animated.timing(this.animatedIsFocused, {
      toValue: this.state.isFocused || this.props.value !== '' ? 1 : 0,
      duration: 200,
    }).start();
  }

  handleFocus = () => {
    this.setState({ isFocused: true });
    if (this.props.onFocus) {
      this.props.onFocus();
    }
  };

  handleBlur = () => this.setState({ isFocused: false });

  focus() {
    this.ref.focus();
  }

  blur() {
    this.ref.blur();
  }

  updateCursorPosition() {
    this.ref.setNativeProps({
      selection: { start: 0, end: 0 },
    });
    this.ref.setNativeProps({
      selection: {
        start: this.props.value.length,
        end: this.props.value.length,
      },
    });
  }

  showAlert = helpText => {
    Alert.alert(helpText.title, helpText.body, [{ text: helpText.button }], {
      cancelable: helpText.cancelable,
    });
  };

  render() {
    const { label, style, isShowingRightAccessory, ...props } = this.props;
    const labelStyle = {
      position: 'absolute',
      left: 0,
      top: this.animatedIsFocused.interpolate({
        inputRange: [0, 0.9],
        outputRange: [15, 0],
      }),
      fontSize: this.animatedIsFocused.interpolate({
        inputRange: [0, 1],
        outputRange: [18, 14],
      }),
    };
    return (
      <View
        style={[
          this.props.style,
          { paddingTop: 18, opacity: this.props.editable ? 1 : 0.5 },
        ]}>
        <Animated.Text
          style={[
            labelStyle,
            {
              color: colors.lightBlue,
            },
          ]}
          allowFontScaling={false}>
          {label}
        </Animated.Text>
        <TextInput
          {...props}
          caretHidden={false}
          underlineColorAndroid="transparent"
          ref={c => {
            this.ref = c;
          }}
          selectionColor={colors.lightBlue}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
          blurOnSubmit
          allowFontScaling={false}
        />
        {this.props.showHelp && (
          <TouchableOpacity
            style={{
              marginTop: 20,
              position: 'absolute',
              alignSelf: 'flex-end',
            }}
            onPress={() => this.showAlert(this.props.helpText)}>
            <Image
              style={{
                height: 15,
                width: 15,
              }}
              source={require('../../assets/icon_Tooltip.png')}
            />
          </TouchableOpacity>
        )}

        <View style={{ height: 1, width: '100%', backgroundColor: 'white' }} />
      </View>
    );
  }
}


 My guess is that I want to implement a ref based solution and I'm looking for advice on how to do that with a custom text component

Upvotes: 3

Views: 14352

Answers (1)

Almost_Ashleigh
Almost_Ashleigh

Reputation: 534

Alright, so I was able to achieve this with useRef in the following way:

const billingFirstNameInput = useRef(null);

<FloatLabelTextInput
          value={billingFirstName}
          onChangeText={newText => setBillingFirstName(newText)}
          autoCorrect={false}
          style={globalStyles.textInput}
          label="Billing First Name"
          ref={billingFirstNameInput}
          onSubmitEditing={() => {
            billingLastNameInput.current.focus()
          }}
        />

Upvotes: 7

Related Questions