I have this category filter component in my react native application. For the first time this component is loaded it does not scroll to given index item (i.e 3). I checked and the function scrollToIndex
is calling. But after loading the screen when do component re-rendering it is working.
Why does it not scroll down at the first time screen loaded ?
import React, { useCallback, useRef } from 'react'
import { StyleSheet, TouchableOpacity, FlatList, View } from 'react-native'
import { Badge, Text } from 'native-base'
import { connect } from 'react-redux'
import * as categoryActions from '../../Redux/Actions/categoryActions'
import { useFocusEffect } from '@react-navigation/native'
const CategoryFilter = (props) => {
const flatlistRef = useRef()
const handleSetSelectedCategoryId = (categoryId) => {
props.setSelectedCategoryId(categoryId)
}
const getItemLayout = (data, index) => ({
length: 50,
offset: 50 * index,
index,
})
const scrollToIndex = () => {
console.log('scroll to index called !')
let index = 3
flatlistRef.current.scrollToIndex({ animated: true, index: index })
}
useFocusEffect(
useCallback(() => {
scrollToIndex()
}, [])
)
const renderItem = ({ item, index }) => {
return (
<TouchableOpacity
key={item._id}
onPress={() => {
handleSetSelectedCategoryId(item._id)
}}
>
<Badge
style={[
styles.center,
{ margin: 5, flexDirection: 'row' },
item._id == props.selectedCategoryId
? styles.active
: styles.inactive,
]}
>
<Text style={{ color: 'white' }}>{item.name}</Text>
</Badge>
</TouchableOpacity>
)
}
return (
<View>
<FlatList
data={props.categories}
renderItem={renderItem}
keyExtractor={(item) => item._id}
horizontal={true}
ref={flatlistRef}
getItemLayout={getItemLayout}
/>
</View>
)
}
....