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

// 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}>
            Add Image
        </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

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 (macOS only)

react-native run-ios

Download Source Code

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.