How to auto-scroll to a focused TextInput in a ScrollView

less than 1 minute read

I couldn’t come up with a more catchy name so this is it! In this blog post I’ll show you how to auto-scroll to a focused TextInput in a ScrollView.

Problem

What I’m working on right now is a clone of this app called 3 good things. The idea behind 3 good things is that writing down three things that you are grateful for every day boosts your mood and mental wellbeing.

Anyway, that’s not the main point. The main point is that the app has a neat feature which makes your screen auto-scroll to whatever input you are focusing, demonstrated here:

So… how do we build this?

Solution

I spent so much time on this and the solution turned out to be really simple: instead messing with ScrollView and KeyboardAvoidingView, just use KeyboardAwareScrollView:

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'

<KeyboardAwareScrollView extraHeight={120}>
  <Card/>
  <Card/>
  <Card/>
  <Card/>
  <Card/>
  <Card/>
</KeyboardAwareScrollView>

Result

And this is what you get:

Notice that nothing happens when you focus the top input, but when you focus the bottom input it automatically scrolls with you. Nice.

Subscribe

Comments