Open In App

Create a Coin Flipping App using React-Native

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article we’ll create a coin flipping app using React-Native. It allows users to simulate the flip of a coin and displays the result as either “Heads” or “Tails” with a corresponding image. The user can see the count of head and tails and can even reset the score.

Preview of final output : Let us have a look at how the final output will look like.

localhost_19006_(Moto-G4)

Prerequisites :

  • Node.js and npm installed on your computer
  • Expo CLI (Expo is a framework for building React Native apps)
  • A code editor (e.g., Visual Studio Code)

Approach:

  • The app uses React Native to create a user interface.
  • It has a button that, when pressed, triggers a function to flip the coin.
  • The coin flip is simulated using a random number (0 or 1).
  • Depending on the random result, the app displays “Heads” or “Tails” corresponding image.

Steps to Create the Project:

Step 1 : Create a new Expo project:

npx create-expo-app CoinFlipping

Step 2 : Navigate to the project directory:

cd CoinFlipping

Step 3: Add coin images (heads.jpg and tails.jpg) to the project’s “assets” directory.

Step 4: Run the app with expo start and open it in the Expo Go app or an emulator.

Project Structure:

Screenshot-2023-10-16-212822

project structure

Example :Write the following code in your App.js file.

Javascript




// App.js
import React, { useState, useRef } from "react";
import {View,Text,Image,Button,StyleSheet,TouchableOpacity,Animated,Easing,
} from "react-native";
  
const App = () => {
    const [coinSide, setCoinSide] = useState("Heads");
    const [headsCount, setHeadsCount] = useState(0);
    const [tailsCount, setTailsCount] = useState(0);
  
    const flipAnimation = useRef(new Animated.Value(0)).current;
    const animatedValue = useRef(new Animated.Value(0)).current;
  
    const flipCoin = () => {
        const randomSide = Math.floor(Math.random() * 2);
  
        // Create a flip animation
        Animated.timing(flipAnimation, {
            toValue: 3,
            duration: 1000,
            easing: Easing.linear,
            useNativeDriver: true,
        }).start(() => {
            // Reset the animation value and set the
            // coin side based on the random result
            flipAnimation.setValue(0);
            if (randomSide === 0) {
                setCoinSide("Heads");
                setHeadsCount(headsCount + 1);
            } else {
                setCoinSide("Tails");
                setTailsCount(tailsCount + 1);
            }
        });
    };
  
    const resetCounts = () => {
        setHeadsCount(0);
        setTailsCount(0);
    };
  
    return (
        <View style={styles.container}>
            <Text style={styles.title}>Coin Flip App</Text>
            <View style={styles.coinContainer}>
                {coinSide && (
                    <Animated.Image
                        source={
                            coinSide === "Heads"
                                ? require("./assets/heads.jpg")
                                : require("./assets/tails.jpg")
                        }
                        style={[
                            styles.coinImage,
                            {
                                transform: [
                                    {
                                        rotateY: flipAnimation.interpolate({
                                            inputRange: [0, 1],
                                            outputRange: ["0deg", "180deg"],
                                        }),
                                    },
                                ],
                            },
                        ]}
                    />
                )}
            </View>
            <View style={styles.countContainer}>
                <View style={styles.count}>
                    <Text style={styles.countText}>Heads: {headsCount}</Text>
                </View>
                <View style={styles.count}>
                    <Text style={styles.countText}>Tails: {tailsCount}</Text>
                </View>
            </View>
            <View style={styles.buttonRow}>
                <TouchableOpacity style={styles.button} onPress={flipCoin}>
                    <Text style={styles.buttonText}>Flip Coin</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.button} onPress={resetCounts}>
                    <Text style={styles.buttonText}>Reset</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
};
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
    },
    title: {
        fontSize: 24,
        fontWeight: "bold",
        marginBottom: 20,
    },
    coinContainer: {
        marginBottom: 30,
    },
    coinImage: {
        width: 150,
        height: 150,
    },
    countContainer: {
        flexDirection: "row",
        marginBottom: 10,
    },
    count: {
        marginRight: 20,
    },
    countText: {
        fontSize: 18,
        fontWeight: "bold",
        color: "#007BFF",
    },
    buttonRow: {
        flexDirection: "row",
    },
    button: {
        backgroundColor: "#007BFF",
        padding: 10,
        margin: 10,
        borderRadius: 5,
    },
    buttonText: {
        color: "white",
        fontWeight: "bold",
    },
});
  
export default App;


Steps to Run the Application:

Step 1: Go to the Terminal and type the following command to run the react native application.

npx expo start

Step 2: Based on your operating system the the following command.

  • To run on Android:
npx react-native run-android
  • To run on ios:
npx react-native run-ios

Output:

screen-capture

output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads