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
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
Related
I have a flatlist that shows a messages chat. I want to start at the bottom of the flatlist (showing the most recent messages). I added 'inverted={true}' and 'data={data.reverse()}' as the props.
It is sort of working, but the data alternates being reversed and not reversed every time i leave and enter the chat again.
Anyone know the fix?
Attached code
.reverse() mutates the original list.
If you do want your list reversed, do it like this
const App = ({ data }) => {
const reversed = [...data].reverse(); // Make a shallow copy, then reverse the copy
return <Flatlist data={reversed} inverted />;
};
However, you will probably notice that you don't want your list reversed, because inverted is already reversed.
const App = ({ data }) => {
return <Flatlist data={data} inverted />;
};
Say that I have a component where I create child components based on the number of elements passed from the parent ( think of it as a page indicator, for example ).
What I would like to do, is to animate the transition between these dots (their backgroundColor) depending on which one is active.
I have tried in a few ways to match the current value to the index of the child element, however, since I don't have the index beforehand, my attemps have failed.
I am posting the basic component down there without my fail attemps to animate it so it illustrates better what I am talking about.
How would one go about doing that in reanimated 2?
const component = ({active, amountOfDots}) => {
const dotsArray = Array(amountOfDots).fill(0);
return (
<View style={{}}>
{dotsArray.map(() => {
return <Animated.View style={{}} />;
})}
</View>
);
};
I am new to ReactNative and have encountered an issue regarding page refreshing. I have some filters in my screen and will like the page to refresh once any of these filters are pressed, but am unable to find any guides on how to do so. I have searched endlessly but only found numerous guides on refreshing with pulldown, and I feel like the solution has something to do with React.useEffect but am unfamiliar with that.
The important parts of my code are as below:
The TouchableOpacity component to trigger the refresh:
<TouchableOpacity
style={styles.filterButton}
onPress={() => {
sortByRating()
}}
>
where sortByRating() is a function to sort my eateriesToShow array based on their ratings.
The FlatList I want to be refreshed on filter:
<FlatList
data={eateriesToShow}
keyExtractor={item => item.id.toString()}
renderItem={renderItem}
showsVerticalScrollIndicator={true}
/>
</View>
)
}
Currently my eateriesToShow array gets sorted, but the FlatList does not get refreshed. Any help will be appreciated.
You want your flatist to update when the data is changed. refreshing your flautist is another thing. So what I suggest you to do is use the useState hook.
const [yourList, setYourList] = useState<string | null>(null)
like this (you don't need the types if you are using javascript instead of typescript)
and then when sorting by rating you should do setYourList(newEateriesArray)
and your flautist should update.
I have a flatlist in a react-native app. This flatlist is filled with an array (renderItem). This works.
When I click on an item in the flatlist, the item should dissapear.
const [currentValues, setCurrentValues] = useState([])
// a fetch fills the currentValues-array with data from a
// database here, this works
<FlatList
data={currentValues}
renderItem={(item, index) => {
return (
<TouchableOpacity onPress={() => deleteItem(item.id)} style={{ borderWidth: 1, borderColor: 'black' }}>
<Text>{item.username}</Text>
</TouchableOpacity>
)
}} />
With the following function, I delete the item from the array:
const deleteItem = id => {
let array = currentValues
let index = array.findIndex(e => e.id === id)
array.splice(index, 1)
setCurrentValues(array)
}
The following problem occurs:
The deletion of the item in the array works, because when I do a console.log, I see the array is empty. The FlatList however does not re-render. When I click on an item to delete it, the username disappears (because it's deleted from the currentValues-item), but the item itself is not deleted, I still see a bordered rectangle.
When I just reset the array after I click one item, it works, so then the FlatList is re-rendered like it should. But then, all items are deleted at once (because I clear the array), and that's not what I want.
I tried the extraData prop. I added this to my flatlist:
extraData={currentValues}
I want to make sure the FlatList re-renders when the currentValues-array is updated, but this also does not work.
Does anyone knows how to solve this?
BTW, changing from FlatList to ScrollView works (with the exact same functions). So I think it's a FlatList issue.
Solution
The solution (based on MBach's answer):
const deleteItem = id => {
let array = [...currentValues]
let index = array.findIndex(e => e.id === id)
array.splice(index, 1)
setCurrentValues([...array])
}
Try to force clone your array with spread operator:
let array = [...currentValues]
Or you can connect currentValues to useEffect()
I am trying to use RN flatlist to show a large list of contact names (100+ items). I keep getting the following warning:
VirtualizedList: You have a large list that is slow to update - make
sure your renderItem function renders components that follow React
performance best practices like PureComponent, shouldComponentUpdate,
etc.
Certain animated UI items get very sluggish whenever the list has more than 50 items in it, however the sluggishness gets a lot better once I scroll all the way down to the bottom of the list
I grab all the contacts in one go and store them in an array in a redux store. I have tried using props like initialNumToRender but cant seem to improve performance. Is there anything I can do to improve my list? I have never used RN FlatList before so any tips would be appreciated
Here is my list related code:
renderRow = ({item}) => {
return (
<ListItem
title={item.firstName}
chevronColor={colors.tertiary}
/>
)
}
<FlatList
data={this.props.contacts}
renderItem={this.renderRow}
keyExtractor={item => item.id}
initialNumToRender={10}
removeClippedSubviews={true}
/>
this.props.contacts is the array of contact objects in the redux store
I ended up implementing recyclerlistview and followed this tutorial which explained how to get it working since the documentation is lacking. Its working miles better than flat list did. Very fast and smooth.
You can follow these code implementations.
For VIEWABILITY_CONFIG follow this link
const VIEWABILITY_CONFIG - {
minimumViewTime: 300,
viewAreaCoveragePercentThreshold: 100,
waitForInteraction
}
const yourItemHeight = 108;
class yourClass extends React.PureComponent
...
_getItemLayout(data, index) {
return { lenght: yourItemHeight, offset: yourItemHeight * index, index }
}
<FlatList
data={this.props.contacts}
renderItem={this.renderRow}
keyExtractor={item => item.id}
getItemLayout: {this._getItemLayout}
initialNumToRender={10} // Vary According to your screen size take a lumsum according to your item height
removeClippedSubviews={true}
viewabilityConfig={VIEWABILITY_CONFIG}
/>