# React NativeのFlatListで要素がデバイスの高さ分存在しないときに、onEndReachedが発火する問題を解決する

1 min read

React Nativeで無限スクロールのタイムラインを作成したんだけど、対象のコンテンツがデバイスの高さ以上になるコンテンツ数を持っていないときに、発生する必要のない無限スクロールイベントが無限で発生する事象が起きたので対処法を実装した。

まずはデバイスの高さを取得する。

const screenHeight = Dimensions.get("window").height;

次にFlatListののコンテンツサイズ変更時にsetContentHeightを利用し、リストの高さを更新する

const [contentHeight, setContentHeight] = useState(0);
...(中略)
onContentSizeChange={(width, height) => {
setContentHeight(height);
}}

で、リストの高さがデバイスの高さより大きければ、スクロール可能(onEndReachedが発火してもいい)ので

const hasMoreContent = contentHeight > screenHeight;
...(中略)
onEndReached={hasMoreContent ? onEndReached : null}
}}

という風に実装できる。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments