0

I have a horizontal ScrollView, on which I wanted to have scroll functionality, where onPress it should scroll to right. I am using functional component.

Below is the snippets from my code:

const scroll = React.createRef();

<TouchableOpacity onPress={()=>{scroll.current.scrollTo({x: 0})}}}>

<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.horizontalView}
 ref={scroll}
>

<TouchableOpacity onPress={() => {scroll.current.scrollTo({x: 100})}}>

I saw above solution while I was searching for one. But this is giving me error: Cannot read property 'scrollTo' of null. I have been hitting my head for hours, but not able to do it. Please help.

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • We'd need to see your whole component to help. My best guess is that you are using a functional component right now, and you are referring to a scroll ref like it was a class component. – Lukasz Jan 22 '21 at 22:59
  • yes, it is a functional component. what changes should I make to make it work in functional component?? – pratteek shaurya Jan 23 '21 at 05:04

1 Answers1

1

You should use useRef as below:

const scroll = useRef();
maltoze
  • 717
  • 7
  • 18