Home > Software design >  Why is the type of ref not recognized in the child component?
Why is the type of ref not recognized in the child component?

Time:11-01

I'm passing a component in a ScrollView and there I pass the ref too.

const GameMulti: FC<GameMultiProps> = ({ navigation }) => {
  const scrollViewRef = useRef<ScrollView & scrollViewProps>(null);
// Should be:
// const scrollViewRef = useRef<ScrollView & React.RefObject<ScrollView>>(null);
...

 <ScrollView
          ref={scrollViewRef}

>

  <DetailedAnswer
    scrollViewRef={scrollViewRef}
  />

...

DetailedAnswer.tsx

export type scrollViewProps = {
  current: {
    scrollTo: ({ y, animated, }: { y: number, animated: boolean }) => { y: number, animated: boolean }
  }
};

interface Props {
  scrollViewRef: ScrollView & scrollViewProps
// Should be:
// scrollViewRef: React.RefObject<ScrollView>
}

const DetailedAnswer: FC<Props> = ({ scrollViewRef }) => {

  if (scrollViewRef.current) // not needed
    scrollViewRef.current?.scrollTo({ y: 0, animated: true });

I've created the scrollViewProps because the one from react-native was giving me an error with current.

But now I get an error in the above:

 <DetailedAnswer
    scrollViewRef={scrollViewRef}
  />


Type 'RefObject<ScrollView & scrollViewProps>' is not assignable to type 'ScrollView & scrollViewProps'.
  Type 'RefObject<ScrollView & scrollViewProps>' is missing the following properties from type 'ScrollView': scrollTo, scrollToEnd, flashScrollIndicators, getScrollResponder, and 38 more.ts(2322)
DetailedAnswer.tsx(33, 3): The expected type comes from property 'scrollViewRef' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

CodePudding user response:

As @jnelson stated (kinda), type of scrollViewRef should be a RefObject.

interface Props {
  scrollViewRef: React.RefObject<ScrollView>;
}

You don't need to create a seperate type as scrollViewProps.

Also, FYI you don't need to check if scrollViewRef.current is truthy if you're going to use optional chaining. You can remove if (scrollViewRef.current). scrollViewRef.current?.scrollTo will suffice.

  • Related