Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native error on ref scrollview, but working

I need to scroll to bottom of flatlist, so I use:

const scrollViewRef = useRef();


//my scroll view
<ScrollView
    ref={scrollViewRef}
    onContentSizeChange={() => {
        scrollViewRef.current.scrollToEnd({ animated: true });
    }}

but I got these errors:

enter image description here

The first one is:

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ScrollViewProps>): ScrollView', gave the following error.
    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.
        Types of property 'current' are incompatible.
          Type 'undefined' is not assignable to type 'ScrollView | null'.
  Overload 2 of 2, '(props: ScrollViewProps, context?: any): ScrollView', gave the following error.
    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'

the second one is:

Object is possibly 'undefined'.

Any suggestions?

like image 395
samuel Avatar asked Aug 27 '26 22:08

samuel


1 Answers

You need to pass type to useRef and scrollViewRef current can be null so just make a if or use ? operator.

const scrollViewRef = useRef<ScrollView|null>(null);


//my scroll view
<ScrollView
    ref={scrollViewRef}
    onContentSizeChange={() => {
        scrollViewRef?.current?.scrollToEnd({ animated: true });
    }}
like image 183
anthony willis muñoz Avatar answered Aug 30 '26 11:08

anthony willis muñoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!