Lottie で React Native + Expo でアニメーションアイコンを設定する

動くアイコンを設定する方法です。

ライブラリをインストールする

shell
npx expo install lottie-react-native

https://docs.expo.dev/versions/latest/sdk/lottie/

使いたいアイコンを探す

LottieFiles というサイトで使いたいアイコンを探して、 JSON ファイルをダウンロードします。

Lottie を使うコンポーネントを作成

Checkmark.tsx
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { useEffect, useRef } from 'react';
import { AntDesign } from '@expo/vector-icons';
import LottieView from 'lottie-react-native';

interface CheckMarkProps {
  isCompleted: boolean;
  toggleIsCompleted: () => void;
}

export default function CheckMark({ isCompleted, toggleIsCompleted }: CheckMarkProps) {
  const animation = useRef<LottieView>(null);
  useEffect(() => {
    if (isCompleted) {
      animation.current?.play();
    } else {
      animation.current?.reset();
    }
  }, [isCompleted]);

  return (
    <View style={styles.container}>
      {isCompleted ? (
        <TouchableOpacity onPress={toggleIsCompleted}>
          <LottieView
            ref={animation}
            loop={false}
            style={{
              width: 36,
              height: 36,
              backgroundColor: '#fff',
            }}
            // Find more Lottie files at https://lottiefiles.com/featured
            source={require('./checkmark.json')}
          />
        </TouchableOpacity>
      ) : (
        <TouchableOpacity onPress={toggleIsCompleted}>
          <AntDesign name="checkcircleo" size={36} color="lightgray" />
        </TouchableOpacity>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  buttonContainer: {
    paddingTop: 20,
  },
});

コンポーネントと同じディレクトリに LottieFiles からダウンロードした JSON を配置

上のコンポーネントで

source={require('./checkmark.json')}

のようにJSONを読み込んでいます。この JSON ファイルは、LottieFiles というサイトからダウンロードしたものです。自分はコンポーネントと同じディレクトリに配置しました。

別のコンポーネントで呼び出す

<CheckMark isCompleted={item.isCompleted} toggleIsCompleted={toggleCompleted} /> のようにして、別のコンポーネント内で使います。

この例では冒頭のスクリーンショットのように、チェックマークのアニメーションが動きます。