Adding type for useRef on ScrollView react-native

Viewed 2530

Looking to create a ref to a ScrollView component like so: const ref = useRef<ScrollView>(null); (or something to this effect) essentially I need access to the flashScrollIndicators method like this:

<ScrollView
  ref={ref}
  onContentSizeChange={() => ref?.current?.flashScrollIndicators()}>
  {children}
</ScrollView>

The code does work in my app however typescripts definitions for ScrollView doesn't seem to include flashScrollIndicators? I'm getting Property 'flashScrollIndicators' does not exist on type 'ScrollView'.ts(2339) looking through the types I can see SectionList and Flatlist so unsure if this is an bug with the definitions or just me not using it properly.

2 Answers

After some research, I couldn't find any official documentation or blog post with the correct solution but declaring the ref using ScrollView itself worked for me. So you can do something like:

const scrollViewRef = React.useRef<ScrollView>(null);

And then autocomplete will take care of the rest, hope it helps!

Since the flashscrollindicators does exist on ScrollView in documentation (and works in app) https://reactnative.dev/docs/scrollview#flashscrollindicators I assume this is bug in type definition.

I think the cleanest solution is to define your own ScrollViewRef using intersection.

import { ScrollView } from 'react-native';

export type ScrollViewRef = ScrollView & {
    flashScrollIndicators: () => void;
};

then use this type to define the ref

const scrollViewRef = React.useRef<ScrollViewRef | null>(null);
Related