Locking scroll position in FlatList (and ScrollView) - react-native

I'm trying to create a FlatList that keeps the current scroll position locked and does not change by new items that are inserted at the top of the list.
I've created an expo snack to demonstrate my intention.
The snack presents a ScrollView with green items, and a black item at the end.
When the app launch it scrolls to the bottom of the list. After five seconds 10 items are inserted at the top, and the scroll position is changing according to the total size of these items.
This is the code of the expo snack:
import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
const renderItem = ({ item }) => {
let backgroundColor;
if (item == 10) {
backgroundColor = "black"
}
else {
backgroundColor = item % 2 == 0 ? 'green' : 'blue'
}
return (
<View
style={{
width: 200,
height: 50,
backgroundColor,
margin: 10,
}}
/>
);
};
const MyList = class extends Component {
componentDidMount() {
setTimeout(() => this.ref.scrollToEnd({ animated: false }), 500);
}
render() {
return (
<FlatList
ref={r => this.ref = r}
data={this.props.data}
renderItem={this.props.renderItem}
/>
);
}
};
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10],
};
}
componentDidMount() {
const items = [...this.state.items];
items.unshift(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
setTimeout(() => this.setState({ items }), 5000);
}
render() {
return <MyList renderItem={renderItem} data={this.state.items} />;
}
}
I want to keep the scroll position locked, meaning - when items are inserted the scroll position will not change (or at least in a way the user doesn't know anything happened)
Is there a way to do it with the current API of FlatList and ScrollView? What's needed to be implemented to achieve this feature?

you should use componentDidUpdate() to achieve this.
componentDidUpdate(prevProps, prevState) {
if(prevProps.data != this.props.data) {
this.ref.scrollToEnd({ animated: false });
}
}
add this in your MyList component. when component gets receive new props.data and that doesn't to your current props.data then it it will call scrollToEnd.
this might be helpfull!

Have you tried use keyExtractor ? ( https://facebook.github.io/react-native/releases/next/docs/flatlist.html#keyextractor ).
It may help react avoid re-render, so try use unique keys for each item.

Related

How to add show more and show less button and render items according to them in react native

I want to render my 10 items at a time and if there are extra items then show more button should be displayed below and if the user clicks it then 10 more should be displayed and so on. I have the property that tells me if there are items for the next page and if it is null then show more button should not be displayed. I don't know how to do it. I am new to react native and I will be very thankful if someone helps me to get out of this situation.
Will this be helpful?
import React, { useEffect, useState } from 'react';
import { Button, Text, View, } from 'react-native';
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
export default function App() {
const [isMore, setIsMore] = useState(false);
const [showingItems, setShowingItems] = useState([]);
useEffect(() => {
setShowingItems([...items.slice(0, 10)]);
if (items.length >= 10) {
setIsMore(true);
}
}, []);
const handleMore = () => {
setShowingItems(items.slice(0, showingItems.length + 10))
if (showingItems.length + 10 > items.length) {
setIsMore(false);
}
}
return (
<View>
{showingItems.map((x) => (
<Text key={x}>{x}</Text>
))}
{isMore && <Button title="More..." onPress={handleMore} />}
</View>
);
};
I created the above without that property. If you need to add it, you can do it like this
useEffect(() => {
setShowingItems([...items.slice(0, 10)]);
setIsMore(yourProperty);
}, []);
This code will display show more button only if shouldBeDisplayed is true.
shouldBeDisplayed is the prop which tell whether to show 10 more or not.
return {
<View>
{shouldBeDisplayed && <Button>show more</Button>}
</View>
}

How to make a custom Radio Button with animation? React Native

I've made a custom Radio Button in React Native. Below is the link to my code.
https://gist.github.com/shubh007-dev/0d8a0ca4d6f7d1530f3e28d223f9199e
What I want is to animate the radio button when I press it, like it's done in this library - https://www.npmjs.com/package/react-native-simple-radio-button
I'm able to animate my radio button for the first time but when I press another radio button, animation doesn't happen.
(Another approach for this question) How can I make sure that the Animated value is different for each Radio Button?
You either have to make a custom component for the radio or use x animated variable for x radio buttons.
Now, making x variable for x buttons is not an efficient solution but it could be used if you got only a few buttons.
You made a custom component which renders a flatlist and that's the problem; can't animate buttons separately in the same component you use to render them.
You should split your code and make the radio button a component itself.
Something like that (didn't test it, but that way it should work) :
export class RadioButton extends Component {
constructor(props) {
super(props);
this.state = {
radioSelected: this.props.selectedItemId,
};
}
radioClick = id => {
this.setState({ radioSelected: id });
this.props.onChange(id);
}
renderRadioButton = item => {
const { radioSelected } = this.state;
const { labelLeftStyle, labelRightStyle, labelOnRight } = this.props;
return (
<AnimatedRadio
{...item}
isSelected={item.id === radioSelected}
labelLeftStyle={labelLeftStyle}
labelRightStyle={labelRightStyle}
labelOnRight={labelOnRight}
radioClick={this.radioClick}
/>
);
};
render() {
return (
<FlatList
data={this.props.radioOptions}
extraData={this.state}
renderItem={({ item }) => this.renderRadioButton(item)}
keyExtractor={(item, index) => index.toString()}
/>
);
}
}
export class AnimatedRadio extends Component {
springValue = new Animated.Value(1.1);
onRadioClick = id => () => {
const { radioClick } = this.props;
radioClick(id);
this.spring();
};
spring = () => {
Animated.spring(this.springValue, {
toValue: 0.95,
friction: 2,
tension: 15,
}).start();
};
render() {
const {
id,
label,
labelLeftStyle,
labelRightStyle,
labelOnRight,
isSelected,
} = this.props;
return (
<View key={id} style={STYLES.radioContainerView}>
<TouchableOpacity
style={STYLES.radioButtonDirectionStyle}
onPress={this.onRadioClick(id)}
>
{labelOnLeft == true ? (
<Text style={[labelLeftStyle]}>{label}</Text>
) : null}
<View
style={[isSelected ? STYLES.selectedView : STYLES.unselectedView]}
>
{isSelected ? (
<Animated.View
style={[
STYLES.radioSelected,
{ transform: [{ scale: this.springValue }] },
]}
/>
) : null}
</View>
{labelOnRight == true ? (
<Text style={[labelRightStyle]}>{label}</Text>
) : null}
</TouchableOpacity>
</View>
);
}
}
This way each component radio will have its own animated value, and won't interfere with others buttons.
I did it using LayoutAnimation like below.
LayoutAnimation.configureNext({
duration: 300,
create: {
type: 'linear',
property: 'scaleXY',
},
update: {
type: 'spring',
springDamping: 0.4,
property: 'opacity',
},
delete: {
type: 'easeOut',
property: 'opacity',
},
});

Toggling the animated value in order to fade in/out the view

I'm trying to toggle view's opacity with animated value, by handling the button click, but I'm not getting the desired result, except the first time button is clicked, it fades out (opacity = 0) but when I press the button again nothing happens and I can't see my view. Here's the code:
export default class App extends React.Component {
state = {
animation: new Animated.Value(1)
}
startAnimation = () => {
const { animation } = this.state
Animated.timing(animation, {
toValue: animation === 0 ? 1 : 0,
duration: 1000
}).start()
}
render() {
const animatedStyle = {
opacity: this.state.animation
}
return (
<View style={styles.container}>
<Animated.View style={[styles.box, animatedStyle]} />
<Button title="Toggle fade" onPress={this.startAnimation} />
</View>
);
}
} .
Does anybody know what am I doing (understanding) wrong?
Thanks!
I think it is because you don't change the state for your animated values, and this const { animation } = this.state will have always the same value, and toValue: animation === 0 ? 1 : 0, will have the same value too. I try to show you how I did this in my projects, but you have to update it for your needs.
export default class App extends React.Component {
state = {
animation: new Animated.Value(1),
isVisible: false //add a new value to check your state
}
startAnimation = () => {
const { isVisible } = this.state
Animated.timing(animation, {
toValue: isVisible === 0 ? 1 : 0,
duration: 1000
}).start(() => {
this.setState({ isVisible: !this.state.isVisible });//set the new state, so the next click will have different value
})
}
render() {
const animatedStyle = {
opacity: this.state.animation
}
return (
<View style={styles.container}>
<Animated.View style={[styles.box, animatedStyle]} />
<Button title="Toggle fade" onPress={this.startAnimation} />
</View>
);
}
} .
I am using this:
let val = this.state.sliderOpen ? 0.8 : 0;
Animated.timing( // Animate over time
this.state.sliderAnimation, // The animated value to drive
{
toValue: val, // Animate to opacity: 1 (opaque)
duration: 5, // Make it take a while
}
).start();
this.setState({
sliderOpen : !this.state.sliderOpen
})
Maybe try to extract the value to be changed.
Thanks to #oma I was able to get it work, here's the snack:
Toggle opacity in React Native
Besides that, I've found a nice article on this where this feature can be reused:
Animating appearance and disappearance in React Native
And here's the snack of the working example, with slight modification.
Animate opacity
This solution looks pretty well, hope you can benefit from it.
I made a node package react-native-fade-in-out that toggles a view's opacity with an animated value. You can look at the source code to see how it is accomplished, but here's a simplified version:
import React, {PureComponent} from 'react';
import {Animated} from 'react-native';
export default class FadeInOut extends PureComponent {
state = {
fadeAnim: new Animated.Value(this.props.visible ? 1 : 0),
};
componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
Animated.timing(this.state.fadeAnim, {
toValue: prevProps.visible ? 0 : 1,
duration: 300,
}).start();
}
}
render() {
return (
<Animated.View style={{...this.props.style, opacity: this.state.fadeAnim}}>
{this.props.children}
</Animated.View>
);
}
}

Scrolling issues with FlatList when rows are variable height

I'm using a FlatList where each row can be of different height (and may contain a mix of both text and zero or more images from a remote server).
I cannot use getItemLayout because I don't know the height of each row (nor the previous ones) to be able to calculate.
The problem I'm facing is that I cannot scroll to the end of the list (it jumps back few rows when I try) and I'm having issues when trying to use scrollToIndex (I'm guessing due to the fact I'm missing getItemLayout).
I wrote a sample project to demonstrate the problem:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Image, FlatList } from 'react-native';
import autobind from 'autobind-decorator';
const items = count => [...Array(count)].map((v, i) => ({
key: i,
index: i,
image: 'https://dummyimage.com/600x' + (((i % 4) + 1) * 50) + '/000/fff',
}));
class RemoteImage extends Component {
constructor(props) {
super(props);
this.state = {
style: { flex: 1, height: 0 },
};
}
componentDidMount() {
Image.getSize(this.props.src, (width, height) => {
this.image = { width, height };
this.onLayout();
});
}
#autobind
onLayout(event) {
if (event) {
this.layout = {
width: event.nativeEvent.layout.width,
height: event.nativeEvent.layout.height,
};
}
if (!this.layout || !this.image || !this.image.width)
return;
this.setState({
style: {
flex: 1,
height: Math.min(this.image.height,
Math.floor(this.layout.width * this.image.height / this.image.width)),
},
});
}
render() {
return (
<Image
onLayout={this.onLayout}
source={{ uri: this.props.src }}
style={this.state.style}
resizeMode='contain'
/>
);
}
}
class Row extends Component {
#autobind
onLayout({ nativeEvent }) {
let { index, item, onItemLayout } = this.props;
let height = Math.max(nativeEvent.layout.height, item.height || 0);
if (height != item.height)
onItemLayout(index, { height });
}
render() {
let { index, image } = this.props.item;
return (
<View style={[styles.row, this.props.style]}>
<Text>Header {index}</Text>
<RemoteImage src = { image } />
<Text>Footer {index}</Text>
</View>
);
}
}
export default class FlatListTest extends Component {
constructor(props) {
super(props);
this.state = { items: items(50) };
}
#autobind
renderItem({ item, index }) {
return <Row
item={item}
style={index&1 && styles.row_alternate || null}
onItemLayout={this.onItemLayout}
/>;
}
#autobind
onItemLayout(index, props) {
let items = [...this.state.items];
let item = { ...items[index], ...props };
items[index] = { ...item, key: [item.height, item.index].join('_') };
this.setState({ items });
}
render() {
return (
<FlatList
ref={ref => this.list = ref}
data={this.state.items}
renderItem={this.renderItem}
/>
);
}
}
const styles = StyleSheet.create({
row: {
padding: 5,
},
row_alternate: {
backgroundColor: '#bbbbbb',
},
});
AppRegistry.registerComponent('FlatListTest', () => FlatListTest);
Use scrollToOffset() instead:
export default class List extends React.PureComponent {
// Gets the total height of the elements that come before
// element with passed index
getOffsetByIndex(index) {
let offset = 0;
for (let i = 0; i < index; i += 1) {
const elementLayout = this._layouts[i];
if (elementLayout && elementLayout.height) {
offset += this._layouts[i].height;
}
}
return offset;
}
// Gets the comment object and if it is a comment
// is in the list, then scrolls to it
scrollToComment(comment) {
const { list } = this.props;
const commentIndex = list.findIndex(({ id }) => id === comment.id);
if (commentIndex !== -1) {
const offset = this.getOffsetByIndex(commentIndex);
this._flatList.current.scrollToOffset({ offset, animated: true });
}
}
// Fill the list of objects with element sizes
addToLayoutsMap(layout, index) {
this._layouts[index] = layout;
}
render() {
const { list } = this.props;
return (
<FlatList
data={list}
keyExtractor={item => item.id}
renderItem={({ item, index }) => {
return (
<View
onLayout={({ nativeEvent: { layout } }) => {
this.addToLayoutsMap(layout, index);
}}
>
<Comment id={item.id} />
</View>
);
}}
ref={this._flatList}
/>
);
}
}
When rendering, I get the size of each element of the list and write it into an array:
onLayout={({ nativeEvent: { layout } }) => this._layouts[index] = layout}
When it is necessary to scroll the screen to the element, I summarize the heights of all the elements in front of it and get the amount to which to scroll the screen (getOffsetByIndex method).
I use the scrollToOffset method:
this._flatList.current.scrollToOffset({ offset, animated: true });
(this._flatList is ref of FlatList)
So what I think you can do and what you already have the outlets for is to store a collection by the index of the rows layouts onLayout. You'll want to store the attributes that's returned by getItemLayout: {length: number, offset: number, index: number}.
Then when you implement getItemLayout which passes an index you can return the layout that you've stored. This should resolve the issues with scrollToIndex. Haven't tested this, but this seems like the right approach.
Have you tried scrollToEnd?
http://facebook.github.io/react-native/docs/flatlist.html#scrolltoend
As the documentation states, it may be janky without getItemLayout but for me it does work without it
I did not find any way to use getItemLayout when the rows have variable heights , So you can not use initialScrollIndex .
But I have a solution that may be a bit slow:
You can use scrollToIndex , but when your item is rendered . So you need initialNumToRender .
You have to wait for the item to be rendered and after use scrollToIndex so you can not use scrollToIndex in componentDidMount .
The only solution that comes to my mind is using scrollToIndex in onViewableItemsChanged . Take note of the example below :
In this example, we want to go to item this.props.index as soon as this component is run
constructor(props){
this.goToIndex = true;
}
render() {
return (
<FlatList
ref={component => {this.myFlatList = component;}}
data={data}
renderItem={({item})=>this._renderItem(item)}
keyExtractor={(item,index)=>index.toString()}
initialNumToRender={this.props.index+1}
onViewableItemsChanged={({ viewableItems }) => {
if (this.goToIndex){
this.goToIndex = false;
setTimeout(() => { this.myFlatList.scrollToIndex({index:this.props.index}); }, 10);
}
}}
/>
);
}
You can use onScrollToIndexFailed to avoid getItemLayout
onScrollToIndexFailed={info => {
const wait = new Promise(resolve => setTimeout(resolve, 100));
wait.then(() => {
refContainer.current?.scrollToIndex({
index: pinPosition || 0,
animated: true
});
});
}}

Animate listview items when they are added/removed from datasource

Can someone give me an idea of how this can be done, e.g. animate the height from 0 when added and back to 0 when removed?
Animation when added is easy, just use Animated in componentDidMount with your listRow , for example:
componentDidMount = ()=> {
Animated.timing(this.state._rowOpacity, {
toValue: 1,
duration: 250,
}).start()
}
Animate a component before unmount is much harder in react-native. You should set a handler for ListView. When dataSource changed, diff the data, start Animated to hide removed row, and set new dataSource for ListView.
Here you can get full working example for opacity animation:
import React from 'react-native';
export default class Cell extends React.Component {
constructor(props) {
super(props);
this.state = {
opacity: new React.Animated.Value(0)
};
}
componentDidMount() {
React.Animated.timing(this.state.opacity, {
toValue: 1,
duration: 250,
}).start();
}
render() {
return (
<React.Animated.View style={[styles.wrapper, {opacity: this.state.opacity}]}>
<React.Image source={{uri: 'http://placehold.it/150x150'}} style={styles.image}/>
<React.Text style={styles.text}>
Text
</React.Text>
</React.Animated.View>
);
}
}
const styles = React.StyleSheet.create({
wrapper: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
image: {
height: 40,
width: 40,
marginRight: 16,
backgroundColor: '#C9D5E6'
},
text: {
fontSize: 20
}
});
In case you need for removing an item from the list, here's how to do the ListRow component:
class DynamicListRow extends Component {
// these values will need to be fixed either within the component or sent through props
_defaultHeightValue = 60;
_defaultTransition = 500;
state = {
_rowHeight : new Animated.Value(this._defaultHeightValue),
_rowOpacity : new Animated.Value(0)
};
componentDidMount() {
Animated.timing(this.state._rowOpacity, {
toValue : 1,
duration : this._defaultTransition
}).start()
}
componentWillReceiveProps(nextProps) {
if (nextProps.remove) {
this.onRemoving(nextProps.onRemoving);
} else {
// we need this for iOS because iOS does not reset list row style properties
this.resetHeight()
}
}
onRemoving(callback) {
Animated.timing(this.state._rowHeight, {
toValue : 0,
duration : this._defaultTransition
}).start(callback);
}
resetHeight() {
Animated.timing(this.state._rowHeight, {
toValue : this._defaultHeightValue,
duration : 0
}).start();
}
render() {
return (
<Animated.View
style={{height: this.state._rowHeight, opacity: this.state._rowOpacity}}>
{this.props.children}
</Animated.View>
);
}
}
i've posted a complete tutorial to this question in this blog post. And it's explaining step by step what you need to do to accomplish both adding and removing an item and animate this process.
For adding is pretty straight forward, but for removing looks like it's a little bit more complex.
http://moduscreate.com/react-native-dynamic-animated-lists/
Here's a full example for height and opacity animation. It supports both adding and removing an element. The key point is that you need to reset the height and opacity after the disappearing animation completes. Then you immediately delete the item from the source.
export const ListItem = (props: ListItemProps) => {
// Start the opacity at 0
const [fadeAnim] = useState(new Animated.Value(0));
// Start the height at 0
const [heightAnim] = useState(new Animated.Value(0));
/**
* Helper function for animating the item
* #param appear - whether the animation should cause the item to appear or disappear
* #param delay - how long the animation should last (ms)
* #param callback - callback to be called when the animation finishes
*/
const _animateItem = (appear: boolean = true, delay: number = 300, callback: () => void = () => null) => {
Animated.parallel([
Animated.timing(
fadeAnim,
{
toValue: appear ? 1 : 0,
duration: delay,
}
),
Animated.timing(
heightAnim,
{
toValue: appear ? 100 : 0,
duration: delay,
}
),
]).start(callback);
};
// Animate the appearance of the item appearing the first time it loads
// Empty array in useEffect results in this only occuring on the first render
React.useEffect(() => {
_animateItem();
}, []);
// Reset an item to its original height and opacity
// Takes a callback to be called once the reset finishes
// The reset will take 0 seconds and then immediately call the callback.
const _reset = (callback: () => void) => {
_animateItem(true,0, callback);
}
// Deletes an item from the list. Follows the following order:
// 1) Animate the item disappearing. On completion:
// 2) Reset the item to its original display height (in 0 seconds). On completion:
// 3) Call the parent to let it know to remove the item from the list
const _delete = () => {
_animateItem(false, 200, () => _reset(props.delete));
};
return (
<Animated.View
style={{height: heightAnim, opacity: fadeAnim, flexDirection: 'row'}}>
<Text>{props.text}</Text>
<Button onPress={() => _delete()}><Text>Delete</Text></Button>
</Animated.View>
);
}