Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a React Native TextInput to maintain focus after submit?

I could explain what I am trying to do, but this ReactJS example is a walkthrough of exactly what I want. The problem is I can't figure out what the equivelant would be for react native.

Basically, when I press return in the TextInput, I want the text cleared and focus maintained.

Any thoughts?

like image 283
brysgo Avatar asked Apr 02 '15 18:04

brysgo


2 Answers

I've submitted a PR with a blurOnSubmit property.

Set it to false and the TextInput never blurs, onSubmitEditing still fires though.

Hopefully it gets merged. :)

https://github.com/facebook/react-native/pull/2149

like image 103
Dave Sibiski Avatar answered Oct 22 '22 11:10

Dave Sibiski


I came out with following (working) solution:

var NameInput = React.createClass({
  getInitialState() {
    return {
      textValue: ''
    }
  },

  clearAndRetainFocus: function(evt, elem) {
    this.setState({textValue: elem.text});
    setTimeout(function() {
      this.setState({textValue: this.getInitialState().textValue});
      this.refs.Name.focus();
    }.bind(this), 0);
  },

  render() {
    return(
      <TextInput
        ref='Name'
        value={this.state.textValue}
        onEndEditing={this.clearAndRetainFocus} />
    )
  }
});

So, basically when we end editing, we will set the textValue state to the value of the TextInput and right after that (in setTimeout), we switch it back to default (empty) and retain focus on the element.

like image 26
Samuli Hakoniemi Avatar answered Oct 22 '22 10:10

Samuli Hakoniemi