Reputation: 11
I am making my own app using react-native I have some difficulties to do notice function.
We have board and comments, if we get notice that someone writes comment, I want to go to that comments in flatlist comments (there can be many comments in board, so if we just go to board without focusing notice comments, user may be hard to find comments). I searched some example of scrollindex method in flatlist. But I want to go directly without button or input. We have comment id in notice model. So first I think that if we compare comment id in flatlist and set state, we can save index of that comments. But setState() doesn't work in flatlist because of error "cannot update a component from inside the function body of a different component." And second, i don't know where we put the function scrollToIndex() because it may move after rendering is finished. But i don't know that state.
IF you know how to solve that problem pleases help me!!
(you can think instagram comment notice, if we click them , we can see that comment, no matter where they were, becauses it automatically move to that comments
Upvotes: 1
Views: 1002
Reputation: 11
getItemLayout = (data, index) => (
{ length: 50, offset: 50 * index, index }
)
getColor(index) {
const mod = index%3;
return COLORS[mod];
}
scrollToIndex = () => {
let randomIndex = Math.floor(Math.random(Date.now()) * this.props.data.length);
this.flatListRef.scrollToIndex({animated: true, index: randomIndex});
}
<FlatList
style={{ flex: 1 }}
ref={(ref) => { this.flatListRef = ref; }}
keyExtractor={item => item}
getItemLayout={this.getItemLayout}
initialScrollIndex={50}
initialNumToRender={2}
renderItem={({ item, index}) => (
<View style={{...style, backgroundColor: this.getColor(index)}}>
<Text>{item}</Text>
</View>
)}
{...this.props}
/>
It is is simple code that use scrolltoindex. It can move to random index item But I want to move certain item doing switch screen. In noticescreen, if we click notice , we need to move board that have that comments. Then we scroll to the comments to show user. We have board id and comments id in notice model. It is not hard to move to the board. But scroll to the comments is hard to me. Any solution?? please
Upvotes: 0