Skip to content

Commit

Permalink
fix: FlatList initialScrollIndex (#233)
Browse files Browse the repository at this point in the history
Co-authored-by: Efstathios Ntonas <stathis@hikiapp.com>
  • Loading branch information
efstathiosntonas and Efstathios Ntonas authored Nov 23, 2023
1 parent 2ba0a0e commit dc550c8
Showing 1 changed file with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { memo } from 'react';
import React, { memo, useRef } from 'react';
import isEqual from 'react-fast-compare';
import { FlatList } from 'react-native';

import { ERRORS, logError } from '../../helpers';
import { NoOptions } from '../no-options';

import type { FlatOptionsListProps } from './flat-options-list.types';
Expand All @@ -16,6 +17,21 @@ export const FlatOptionsList = memo(
accessibilityState,
disabled,
}: FlatOptionsListProps<T>) => {
const flatListRef = useRef<FlatList>(null);

const scrollToIndex = () => {
if (flatListRef.current) {
try {
flatListRef.current.scrollToIndex({
animated: false,
index: initialScrollIndex === -1 ? 0 : initialScrollIndex,
});
} catch {
logError(ERRORS.SCROLL_TO_LOCATION);
}
}
};

return (
<FlatList
testID="Options list"
Expand All @@ -25,13 +41,13 @@ export const FlatOptionsList = memo(
keyboardShouldPersistTaps="handled"
persistentScrollbar={true}
ListEmptyComponent={<NoOptions />}
initialScrollIndex={initialScrollIndex}
scrollEnabled={!disabled}
{...flatListProps}
data={resolvedData}
getItemLayout={getItemLayout}
renderItem={renderItem}
keyExtractor={({ value }) => value}
onLayout={scrollToIndex}
/>
);
},
Expand Down

0 comments on commit dc550c8

Please sign in to comment.