Lynn
Lynn

Reputation: 207

How can I implement animation in my flatlist?

I am using Flatlist in my rn project and when I push new data into my flatlist, my item 1 will automatically move from position A to position B. But my question is I don't want it to just change the position, I want to use animation to move my item(from position A to position B). How can I implement that? Thank you!

Please check the demo picture and video from the link down below: https://photos.app.goo.gl/WypswNyA38A2EAPQA https://photos.app.goo.gl/Ev1RYMduDj7mxrHn7

Upvotes: 2

Views: 3466

Answers (1)

Prasun
Prasun

Reputation: 5023

You can use Animated component to do the animation. As per your attached video, 2 steps animation comes into play, one which pushes the items up in the list and another one which increases the opacity of the list item. A simple approach would be to add the list item with height 0 and increase the height to desired height using animation, this will complete the first step. Once the first step is completed, control the opacity to go from 0 to 1.

Next, you need to start the animation when the list item is added to the list, componentDidMount is the right place to do so. Please consider the following component which does the above steps.

import React from 'react';
import { Animated } from 'react-native';

class AnimatedListItem extends React.Component {
  constructor(...props) {
    super(...props);
    this.state = {
      height: new Animated.Value(0),
      opacity: new Animated.Value(0)
    };
  }

  componentDidMount() {
    Animated.sequence([
      Animated.timing(
        this.state.height,
        {
          toValue: this.props.height,
          duration: this.props.duration || 1000
        }
      ),
      Animated.timing(
        this.state.opacity,
        {
          toValue: 1,
          duration: this.props.duration || 1000
        }
      )
    ]).start();
  }

  render() {
    const { height, opacity } = this.state;
    return (
      <Animated.View
        style={{
          ...this.props.style,
          height: height,
          opacity: opacity
        }}
      >
        {this.props.children}
      </Animated.View>
    );
  }
}

export default AnimatedListItem;

In the above snippet, two animations are passed to Animated.sequence([...]) method to animate one after the other.

You can now use the above component in the renderItem method like

renderItem = () => {
  return (
    <AnimatedListItem height={50} duration={800} style={...}>
      /* render actual component here */
    </AnimatedListItem>
  );
}

Hope this will help!

Note: This is a bare minimum example to achieve what you are looking for.

Upvotes: 1

Related Questions