5

If I have a ScrollView and inside that ScrollView I have many TextInput, how can I scroll the ScrollView to the cursor position when user taps any of TextInput and start typing?

Anytime an user is typing and the cursor passes the ScrollView's visible portion, scroll the ScrollView to make the user can see the cursor.

How can I do that?

user3087000
  • 731
  • 1
  • 13
  • 24
  • I've put a bounty on this issue since I'm experiencing the same problem. The solutions I have seen in here has only solved the issue for one TextInput and I need a working solution for multiple TextInputs on the same ScrollView. – Simon Degn Dec 18 '20 at 19:02
  • It is not perfect but `react-native-gesture-handler` has `ScrollView` and `TextInput`. I use both. They can do some work but not perfectly. – Four Nov 16 '22 at 04:04

2 Answers2

0

After looking into this I might have a possible solution. There is a scrollTo() method for ScrollView which can be used to scroll to a specific position on the screen. And there is a measure() method which can be used to determine a position of a component on a screen. So, you can get the position of the textInput component when it is onFocus and trigger a function which then call the scrollTo() method of the ScrollView.

I haven't tried it so not 100% sure about this.

Resources: How to get the position of a component on screen in react native? https://reactnative.dev/docs/scrollview#scrollto

Sagar Shakya
  • 635
  • 3
  • 7
0

Using References

I have noticed some work arounds such as providing absolute co-ordinates of the component and then adjusting the function and corresponding co-ordinates of the child component from device to device. This is a temporary fix and not really desirable. Here's when the references come into picture.

<Component
    ref={ref => {
      this.compRef = ref;
    }}
/>

once you assign a ref to particular component, you can use react-native's scrollTo() https://reactnative.dev/docs/scrollview#scrollto in order to invoke the scroll event in the UI.

this.compRef.scrollTo({
    //...props here
});

in case one is using functional components, leverage the useRef() https://reactjs.org/docs/hooks-reference.html#useeffect hook to pass references and use them for scrolling.

In order to ship a production ready code, deep linking is always recommended. For more info regarding how to use references and how to connect them with the scrollTo() function in scrollView find an example here: https://arsfutura.com/magazine/deep-linking-in-react-native-scroll-to-element/

enter image description here

source: https://arsfutura.com/magazine/deep-linking-in-react-native-scroll-to-element/

Pratik
  • 73
  • 1
  • 2
  • 9