Docs
Examples
Coin Flip

Coin Flip Example

import React, {useEffect, useState} from 'react';
  import { View, Text, TouchableOpacity, Animated, StyleSheet, SafeAreaView } from 'react-native';
  import {BasicToolbar} from "@components"
  import {MaterialCommunityIcons} from "@expo/vector-icons";
 
 
  function Coin({icon}){
    return (
      <View style={{backgroundColor: "#ffb419", borderRadius: 70, padding: 20, backfaceVisibility: "hidden"}}>
        <MaterialCommunityIcons name={icon} size={100} color="#fff" />
      </View>
    )
  }
 
  function App({exit}) {
    const [animation] = useState(new Animated.Value(0));
    const [result, setResult] = useState('');
    const [emoji, setEmoji] = useState("head")
 
    useEffect(() => {
      const id = animation.addListener(({value}) => {
        if (value === 0 || value === 0.75 || value === 1.5){
          //setEmoji("head")
        }
        if (value === 0.5 || value === 1 || value > 1.5){
          //setEmoji("flower-tulip")
        }
      })
      return () => animation.removeListener(id)
    }, [])
 
    const flipCoin = () => {
      setResult("")
      const flipValue = Math.random();
      const resultText = flipValue < 0.5 ? 'Head' : 'Tail';
 
      setEmoji("progress-question")
      Animated.sequence([
        Animated.timing(animation, {
          toValue: 0.5,
          duration: 200,
          useNativeDriver: true,
        }),
        Animated.timing(animation, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }),
        Animated.timing(animation, {
          toValue: 1.5,
          duration: 500,
          useNativeDriver: true,
        }),
        Animated.timing(animation, {
          toValue: 2,
          duration: 500,
          useNativeDriver: true,
        }),
      ]).start(() => {
        // Reset the animation value once the animation is completed
        animation.setValue(0);
        setResult(resultText);
        setEmoji(resultText === "Head" ? "head" : "flower-tulip")
      });
    };
 
    const interpolateRotation = animation.interpolate({
      inputRange: [0, 0.5, 1, 1.5, 2],
      outputRange: ['0deg', '180deg', '360deg', '180deg', '360deg'],
    });
 
 
    const animatedStyle = {
      transform: [{ rotateY: interpolateRotation }],
    };
    return (
      <SafeAreaView style={{flex: 1}}>
        <BasicToolbar exit={exit} title="Coin Flip" />
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <TouchableOpacity onPress={flipCoin}>
            <Animated.View style={[animatedStyle, { perspective: 1000 }]}>
              <Coin icon={emoji} />
            </Animated.View>
          </TouchableOpacity>
          <Text style={{ fontSize: 30, marginTop: 20 }}>{ result ? `Result: ${result}`: " "}</Text>
        </View>
      </SafeAreaView>
    );
  }
 
 
  export default App;