0

Have tried a few different approaches and can't figure out the exact syntax to pass a ref from the parent to the child. Ultimately I'm trying to make it so that I can scroll to beginning onPress of a Child component. Can someone help me figure it out?

Getting error: `scrollViewRef.scrollTo is not a function'

import React, { useRef } from 'react';
import { ScrollView, Button } from 'react-native';

const Parent = () => {

  const scrollViewRef = useRef();

  const scrollToBeginning = () => {
    scrollViewRef.scrollTo({ x: 0, animated: true });
  }

  return (
    <ScrollView
      ref={ scrollViewRef }
      pagingEnabled
      snapToInterval={ width }
      horizontal
      scrollEventThrottle={16}
      scrollEnabled={ true }
    >
      <Child
        scrollToBeginning={ scrollToBeginning }
      >
    </ScrollView>
  )
}


const Child = (props) => {
  return (
    <Button onPress={ props.scrollToBeginning } title="Scroll To Beginning" />
  )
}
Scott
  • 1,207
  • 2
  • 15
  • 38
  • Function `scrollTo()` does not exist directly on ref. you must use `window.scrollTo` or `ref.current.scrollTo` Check this out: https://stackoverflow.com/questions/43441856/how-to-scroll-to-an-element – Karthick Vinod May 25 '20 at 04:33

1 Answers1

1

You need to use scrollViewRef.current.scrollTo({ x: 0, animated: true }); since the ref property is assigned to the current variable within ref object

const Parent = () => {

  const scrollViewRef = useRef();

  const scrollToBeginning = () => {
    scrollViewRef..current.scrollTo({ x: 0, animated: true });
  }

  return (
    <ScrollView
      ref={ scrollViewRef }
      pagingEnabled
      snapToInterval={ width }
      horizontal
      scrollEventThrottle={16}
      scrollEnabled={ true }
    >
      <Child
        scrollToBeginning={ scrollToBeginning }
      >
    </ScrollView>
  )
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400