Archive

Tag Archives: react-native

I’m still figuring things out with React-Native, but yesterday I was working on getting a form to automatically scroll in order to prevent the keyboard from covering the fields being entered. You’d think this would be built-in behavior for TextInput, but not yet. Maybe eventually. In the meantime, I had to figure out how to make ScrollView work with TextInput, and then make TextInput auto-scroll. The auto-scroll was fairly easy once I found a good StackOverflow post (see the answer from Sherlock) about it, though there were some unanswered bits involved. Getting ScrollView to work with TextInput is sort of straightforward except I stumbled over weird behavior regarding contentContainerStyle.

I’ve made a working example at rnplay.org, so you can check it out at https://rnplay.org/apps/P774EQ. I had to post to StackOverflow with a question at one point because for some reason if you forget the contentContainerStyle, the Text elements inside the ScrollView will still render, but the TextInputs don’t. I’m still not sure why that is, but it made it tricky to figure out the problem. In any case, once everything is rendering the way you want it, then the next thing is to get the auto-scroll working.

As you’ll see in the example, there are a few important steps:

  1. Make sure your ScrollView has the ref=’scrollView’ on it so the inputFocused() function can find it.
  2. Make sure either your TextInput or a wrapper around it has a ref also — this will be passed to the function so that the scroll can find it and position appropriately. In my case I put ref=’firstname’ on the wrapping View.
  3. Next, put the onFocus on the TextInput, and make sure it’s passing the name of the ref. If you have a form with multiple fields, you’ll have this on every TextInput, of course with a different ref for each input. See line 44 in the example.
  4. Then add the inputFocused() function to your code, which is straight from the StackOverflow post referenced above, so thanks again to Sherlock for that. As mentioned in that post, you can tweak the additionalOffset on line 71 if the positioning isn’t quite right based on your layout.

That’s really everything you need to do. I have this working for a view with three form fields, and it scrolls up nicely for each one. Hopefully this is something that will get built-in to TextInput in the future, but for now hopefully this will help out anyone trying to do this.