Skip to content

How update current page of flatlist when scrollToIndex? #36012

@devoren

Description

@devoren

Description

I want to create story view like instagram. I have a horizontal full screen flatlist. And on scroll i update current page. If i debug currentPage in renderItem it not updating. It updating if i use extradata={currentData}. Can we update current page state without extraData?

const scrollHandler = useAnimatedScrollHandler({
	onScroll: (event) => {
		'worklet';
		translationX.value = event.contentOffset.x;
		const newIndex = Math.round(translationX.value / WINDOW.WIDTH);
		if (			newIndex !== currentPage &&
			newIndex < data.length
		) {
			runOnJS(setCurrentPage)(newIndex);
		}
	}})
	
const renderItem: ListRenderItem<IBannerItem> = ({ item, index }) => {
	return (
		<BannerItem
			index={index}
			translationX={translationX}
			key={`${item.banner_id}_${item.banner_name}`}
			currentPage={currentPage}
			onFinish={onFinish}
			customFooterComponent={customFooterComponent}
			customCloseComponent={customCloseComponent}
			onClosePress={onClosePress}
			duration={duration}
			stories={item.stories}
			isScrolling={isScrolling}
			setCurrentPage={setCurrentPage}
		/>
	);
};

const keyExtractor = useCallback(
	({ banner_id, banner_name }: IBannerItem, index: number) =>
		`${banner_id}_${banner_name}`,
	[],
);

return (
	<AnimatedFL
		pagingEnabled
		keyExtractor={keyExtractor}
		ref={ref}
		horizontal
		showsHorizontalScrollIndicator={false}
		bounces={false}
		alwaysBounceHorizontal={false}
		alwaysBounceVertical={false}
		bouncesZoom={false}
		scrollEventThrottle={16}
		onScroll={scrollHandler}
		initialScrollIndex={currentPage}
		renderScrollComponent={ScrollView}
		data={data}
		renderItem={renderItem}
	/>
);

Version

0.71.1

Output of npx react-native info

System:
OS: Windows 10 10.0.19044
CPU: (8) x64 Intel(R) Core(TM) i5-10300H CPU @ 2.50GHz
Memory: 3.17 GB / 15.84 GB
Binaries:
Node: 18.12.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
npm: 9.2.0 - C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK: Not Found
Windows SDK: Not Found
IDEs:
Android Studio: AI-221.6008.13.2211.9477386
Visual Studio: 16.11.31624.102 (Visual Studio Enterprise�2019)
Languages:
Java: 11.0.13 - /c/Program Files/Common Files/Oracle/Java/javapath/javac
npmPackages:
@react-native-community/cli: Not Found
react: 18.2.0 => 18.2.0
react-native: 0.71.1 => 0.71.1
react-native-windows: Not Found
npmGlobalPackages:
react-native: Not Found

Steps to reproduce

  1. Init new RN app
  2. Add horizontal Flat list
  3. Add currentPage useState
  4. onScroll setCurrentPage

Snack, code example, screenshot, or link to a repository

Screenshot_1675156808

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions