Is there a way to do a swipe down to refresh in react native on a regular view without using something like a FlatList or ScrollView ?
There is no built-in solution for doing this. We usually want some kind of feedback for the user, thus the regular pull to refresh
action is a suitable choice and this obviously only works in some kind of scrollable container
.
However, if we still do not want to use a ScrollView
for this purpose, then we could listen to touch gestures and react after a certain treshold as follows.
const SomeRefreshableNonScrollableComponent = (props) => {
const y = useRef()
function onRefresh() {
// refresh or whatever
}
return (
<View
style={{flex :1}}
onTouchStart={e=> y.current = e.nativeEvent.pageY}
onTouchEnd={e => {
// some threshold. add whatever suits you
if (y.current - e.nativeEvent.pageY < 40) {
onRefresh()
}
}}>
...
</View>
)
}
Edit: As an answer to the comments.
We can implement a pull down to refresh mechanism for a FlatList
that is nested inside a not scrollable ScrollView
as follows.
const [data, setData] = useState([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
const [refresh, setRefresh] = useState(false)
useEffect(() => {
if (refresh) {
console.log("Refresh my inner data on pull")
}
}, [refresh])
return (
<ScrollView scrollEnabled={false} nestedScrollEnabled={true}>
<FlatList refreshing={refresh} onRefresh={() => setRefresh(true)} data={data} renderItem={({item}) => {
return <Text>Hello world</Text>
}} />
</ScrollView>
);
};
Notice that you must reset your refresh
state back to false
once your refresh action is done, e.g. if an API call returns its data. Otherwise, the Flatlist will keep showing the refresh indicator.