dinaco
dinaco

Reputation: 95

How to animate a single item from Flatlist

I have a array of data which I render in flatlist in React-Native. On pressing one of the items I want it to fade away, but instead all items on the flatlist get animated and not just the one that I pressed on.

constructor(props){ 
super(props); 
this.state = { fadeAnim: new Animated.Value(1) }



  onPressButtonnotdelivered(item) {
    //Alert.alert(item.name)
      const animations = [
        Animated.timing(this.state.fadeAnim, {
          toValue: 0,
          duration: 500
        }),

      ];

      Animated.sequence(animations).start()
  }


  render() {
return (
  <View>
    <FlatList
      data={this.state.data}
      extraData={this.state}
      keyExtractor={item => item.id}
      renderItem={({ item, index }) => {
        return (
          <Animated.View key={index} style={[styles.animatedview, {opacity: this.state.fadeAnim}]}>
    <View>
    <View style={[styles.button, {backgroundColor: '#E94F64'}]}>
    <TouchableOpacity style={styles.buttonview}
    onPress={() => {this.onPressButtonnotdelivered(item)}}>
  <View style={styles.btnIcon}>
  <Icon name="block" size={30} />
    <Text>Not delivered</Text>
  </View>
</TouchableOpacity>
</View>
          </View>
          </Animated.View>
        );
      }}
    />
  </View>
);
  }

Upvotes: 1

Views: 6538

Answers (2)

Jaydeep Galani
Jaydeep Galani

Reputation: 4961

You need to add one more state to your component say indexToAnimate and set it to null.

Then put one condition in style of <Animated.View>

<Animated.View
        key={index}
        style={[
          styles.animatedview,
          {
            opacity:
              index == this.state.indexToAnimate
                ? this.state.fadeAnim
                : "whatever your static value is..(in integer)"
          }
        ]}
/>

and set indexToAnimate state on onPress method of <TouchableOpacity>

<TouchableOpacity
  style={styles.buttonview}
  onPress={() => {
    this.setState({ indexToAnimate: index }, () => this.onPressButtonnotdelivered(item));
  }}
>
  <View style={styles.btnIcon}>
    <Icon name="block" size={30} />
    <Text>Not delivered</Text>
  </View>
</TouchableOpacity>

Upvotes: 6

Defrian
Defrian

Reputation: 660

What if you add a conditional render to the renderItem like:

renderItem={({ item, index }) => {
    if (index === 'id') 
      return(<Animated.View> ... </Animated.View>);
    else
      return(<View> ... </View>);
 }

Upvotes: 1

Related Questions