'How can I use ScrollTo in React Native?
I'm quite new to React Native, I'm developing an app for advertising where there are categories and adverts listings. I would like to have the animation when the user clicks on a category, the screen should scroll downwards to the section with "Latest Ads". I'm not using ScrollView, I have used two Flatlists one for the categories and the other for products/adverts.
I have tried to use scrollTo() as shown in react native documentation (https://reactnative.dev/docs/scrollview#scrollto)
Please help.
Below is part of my code in my JSX file that gives me an error:
//Scroller code starts
const myScroller = () => {
scrollTo({ x: 0, y: 90, animated: true });
};
// Scroller code ends
const handleSelectCategory = (item) => {
setSearchData((prevSearchData) => {
return { ...prevSearchData, categories: item.term_id, page: 1 };
});
dispatch({
type: "SET_CAT_NAME",
cat_name: [item.name],
});
setLoading(true);
myScroller();
};
Solution 1:[1]
You need to use ref to scroll
import { useRef } from 'react';
...
...
const scrollRef = useRef(null); // inside your function component
...
const myScroller = () => {
scrollRef ?.current ?.scrollTo({ x: 0, y: 90, animated: true });
};
...
<FlatList
ref={scrollRef} // put reference in FlatList which need to scroll
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thanhal |

