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 command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

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

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

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

// How to Add or Remove FlatList Item with Animation
// https://aboutreact.com/add-or-remove-flatlist-item-with-animation/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  UIManager,
  LayoutAnimation,
  TouchableOpacity,
  SafeAreaView,
  Platform,
} from 'react-native';

import Card from './Card';
console.disableYellowBox = true;

if (Platform.OS === 'android') {
  UIManager.setLayoutAnimationEnabledExperimental &&
    UIManager.setLayoutAnimationEnabledExperimental(true);
}
const imageUrl =
  'https://raw.githubusercontent.com/AboutReact/sampleresource/master/logosmalltransparen.png';

const App = () => {
  const [dataSource, setDataSource] = useState([]);

  const 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,
      },
    });
  };

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

  removeItem = (key) => {
    setAnimation();
    setDataSource(
         dataSource.slice().filter((item) => item.key !== key)
    );
  };

  const ItemView = ({item}) => {
    return (
      // Flat List Item
      <Card item={item} removeItem={removeItem} />
    );
  };

  const ItemSeparatorView = () => {
    return (
      // Flat List Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    // Function for click on an item
    alert('Id : ' + item.id + ' Title : ' + item.title);
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <TouchableOpacity
        style={styles.addButtonStyle}
        onPress={addItem}>
        <Text style={styles.addIconStyle}>
            Click to add list item
        </Text>
      </TouchableOpacity>
      <FlatList
        data={dataSource}
        keyExtractor={(item, index) => index.toString()}
        ItemSeparatorComponent={ItemSeparatorView}
        renderItem={ItemView}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  addButtonStyle: {
    width: '100%',
    elevation: 3,
    backgroundColor: '#808080',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 15,
  },
  addIconStyle: {
    color: 'white',
    padding: 10,
    fontSize: 20,
    textAlign: 'center',
  },
});

export default App;

Card.js

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

// How to Add or Remove FlatList Item with Animation
// https://aboutreact.com/add-or-remove-flatlist-item-with-animation/

// import React in our code
import React from 'react';

// import all the components we are going to use
import {
  View,
  StyleSheet,
  Text,
  Image,
  Animated,
  TouchableOpacity,
} from 'react-native';
//Import basic react native components

const Card = (props) => {
  const {removeItem, item} = 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',
  },
});

export default Card;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

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. 🙂

Leave a Comment

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