Search code examples
reactjstypescriptreact-nativescroll

React Native Typescript : scroll with useRef and scrollIntoView


I wanted to be able to scroll to an element when I press on a element. (ex : I press D and it scroll down to the letter D) . Howether while there is no error here, it is not scrolling down. Here is my code simplified:

const fieldRef = React.useRef<null | HTMLInputElement>(null);
  const scrollToElement = () => fieldRef.current?.scrollIntoView();
 

...

                    <Text
                      onPress={() => {
                        {
                          scrollToElement;
                        } }}
                     > 
                         Here
                     </Text>

...

<div ref={fieldRef}>
    <Text> Hello</Text>
</div>

I used these to try to correct my code: How to add "refs" dynamically with react hooks? as well as How to scroll to an element? as well as TypeScript error: Property 'scrollIntoView' does not exist on type 'never'. TS2339


Solution

  • To scroll a certain amount down:

    fieldRef.current!.scroll(0, fieldRef.current!.scrollTop +30)