0

I am using @shoutem/ui library that has it's own TextInput implementation for react native.

https://github.com/shoutem/ui/blob/develop/components/TextInput.js

I'm trying to set focus on the next input on a keyboard next button press like so

React Native: How to select the next TextInput after pressing the "next" keyboard button?

However, Shoutem/ui's implementation doesn't expose a focus() method for the TextInput that I can use from a reference.

How do I expose the TextInput's focus method as a property in the outer class?

import React, { Component } from 'react';
import { TextInput as RNTextInput } from 'react-native';

import { connectStyle } from '@shoutem/theme';
import { connectAnimation } from '@shoutem/animation';

class TextInput extends Component {
  focus() {
     // how do I expose the react native text input focus method from this class?  
     // do I get a reference to the text input component somehow?
  }
  render() {
    const { props } = this;
    const style = {
      ...props.style,
    };
    delete style.placeholderTextColor;
    delete style.selectionColor;

    return (
      <RNTextInput
        {...props}
        style={style}
        placeholderTextColor={props.style.placeholderTextColor}
        selectionColor={props.style.selectionColor}
      />
    );
  }
}

TextInput.propTypes = {
  ...RNTextInput.propTypes,
  style: React.PropTypes.object,
};

const AnimatedTextInput = connectAnimation(TextInput);
const StyledTextInput = connectStyle('shoutem.ui.TextInput')(AnimatedTextInput);

export {
  StyledTextInput as TextInput,
};
Community
  • 1
  • 1
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

1 Answers1

1

You can use refs.

focus() {
    this.rnInput.focus();
}
render() {
    const { props } = this;
    const style = {
    ...props.style,
    };
    delete style.placeholderTextColor;
    delete style.selectionColor;

    return (
    <RNTextInput
        {...props}
        ref={input => this.rnInput = input}
        style={style}
        placeholderTextColor={props.style.placeholderTextColor}
        selectionColor={props.style.selectionColor}
    />
    );
}

A little explanation. The ref callback is executed after the component finishes rendering, you then have a reference for the current instance of this component that you can save in a variable for latter use ref={input => this.rnInput = input}. Now you can use this.rnInput to call the focus method.

Tiago Engel
  • 3,533
  • 1
  • 17
  • 22