How to Add or Remove FlatList Item with Animation

Add or Remove FlatList Item

In this post, we will see How to Add or Remove FlatList Item with Animation. FlatList is the most common thing which you use in the React Native development so here is a basic animation example that will help you to animate your FlatList rendering. We are going to use UIManager from the react-native library to enable layout animation using

UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);

In this example, we are going to make a FlatList and Card as an item of the FlatList. We are making a button at the top of the list, on the click of that button we are going to add the item in the list with animation.

Let’s get started with the example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Now jump into your project using

cd ProjectName

Code

Please create a Card.js file in the project. After creating the file please copy-paste the following code

App.js

Open App.js in any code editor and replace the code with the following code

/*Example to add or remove flatlist item with animation*/
import React, { Component } from 'react';
//Import React
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  UIManager,
  LayoutAnimation,
  TouchableOpacity,
  SafeAreaView
} from 'react-native';
//Import basic react native components
import Card from './Card';
//Import custom card component

console.disableYellowBox = true;

UIManager.setLayoutAnimationEnabledExperimental &&
  UIManager.setLayoutAnimationEnabledExperimental(true);
const imageUrl = 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/logosmalltransparen.png';
const cards = [
  {
    key: 0,
    uri: imageUrl,
    title: 'Animated FlatList Example Heading',
    description: 'Please visit www.aboutreact.com',
  },
];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cards,
    };
  }
  
  setAnimation = () => {
    LayoutAnimation.configureNext({
      duration: 250,
      update: {
        type: LayoutAnimation.Types.easeIn,
        springDamping: 0.7,
      },
    });
    LayoutAnimation.configureNext({
      duration: 500,
      create: {
        type: LayoutAnimation.Types.easeIn,
        property: LayoutAnimation.Properties.scaleXY,
        springDamping: 0.7,
      },
    });
  };

  addItem = (() => {
    let key = cards.length;
    return () => {
      const { cards } = this.state;
      cards.unshift({
        key,
        uri: imageUrl,
        title: 'Animated FlatList Example Heading',
        description: 'Please visit www.aboutreact.com',
        animated: true,
      });
      this.setAnimation();
      this.setState({
        cards: cards.slice(0),
      });
      key++;
    };
  })();

  removeItem = key => {
    const { cards } = this.state;
    this.setAnimation();
    this.setState({
      cards: cards.slice().filter(card => card.key !== key),
    });
  };

  renderItem = ({ item }) => <Card item={item} removeItem={this.removeItem} />;

  render() {
    return (
      <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
        <View style={styles.container}>
        <TouchableOpacity style={styles.addButton} onPress={this.addItem}>
            <Text style={styles.addIcon}>Add Image</Text>
          </TouchableOpacity>
          <FlatList
            contentContainerStyle={styles.paragraph}
            data={this.state.cards}
            renderItem={this.renderItem}
            ItemSeparatorComponent={() => <View style={{ marginTop: 10 }} />}
            keyExtractor={item => item.key.toString()}
          />
        </View>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFF',
  },
  paragraph: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#34495e',
    paddingBottom: 10,
  },
  addButton: {
    width: '100%',
    elevation: 3,
    backgroundColor: '#808080',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 15
  },
  addIcon: {
    color: 'white',
    padding: 10,
    fontSize: 20,
    textAlign: 'center',
  },
});

Card.js

Open Card.js in any code editor and replace the code with the following code

/*Example to add or remove flatlist item with animation*/
import React from 'react';
//Import React
import {
  View,
  StyleSheet,
  Text,
  Image,
  Animated,
  TouchableOpacity,
  SafeAreaView
} from 'react-native';
//Import basic react native components

export default class Card extends React.Component {
  render() {
    const { removeItem, item } = this.props;
    const { uri, title, description, key } = item;
    return (
      <Animated.View style={{ flex:1, alignItems: 'center', paddingVertical:10 }}>
        <TouchableOpacity
          onPress={() => removeItem(key)}
          style={styles.container}>
          <Image style={styles.thumbnail} source={{ uri }} />
          <View style={styles.metaDataContainer}>
            <View style={styles.metaDataContent}>
              <Text style={styles.title}>{title}</Text>
              <Text style={styles.description}>{description}</Text>
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: 80,
    elevation: 3,
    borderColor: 'gray',
    borderRadius: 5,
    flexDirection: 'row',
    marginHorizontal: 20,
  },
  metaDataContainer: {
    flex: 1,
  },
  thumbnail: {
    width: 70,
    height: 70,
  },
  metaDataContent: {
    marginTop: 5,
    marginLeft: 15,
  },
  title: {
    color: '#444',
    fontSize: 18,
    fontWeight: 'bold',
  },
  description: {
    fontSize: 16,
    color: '#888',
    fontWeight: '700',
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

      

This is how to add or remove FlatList items with animation. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.