Open In App

Create a Number Guessing App using React-Native

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Number Guessing App is a simple mobile game where the user tries to guess a random number generated by the app. The app provides feedback to the user, indicating whether their guess is too high or too low, and keeps track of the number of attempts it takes to guess the correct number. In this article, we will learn how to create a Number-Guessing Game using React Native.

Create-a--Number--Guessing

To give you a better idea of what we’re going to create, let’s watch a demo video.

Demo Video

Playground

Note: This Section is to interact with the app which you are going to build.


Prerequisites

Step-by-Step Implementation

Step 1: Create a React Native Project

Now, create a project with the following command.

npx create-expo-app app-name --template

Note: Replace the app-name with your app name for example : react-native-demo-app

Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app that is as clean as an empty canvas in JavaScript.

It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.

Now go into your project folder, i.e., react-native-demo

cd app-name

Project Structure:

Step 2: Run  Application

Start the server by using the following command.

npx expo start

Then, the application will display a QR code.

  • For the Android users,
    • For the Android Emulator, press " a" as mentioned in the image below.
    • For the Physical Device, download the " Expo Go " app from the Play Store. Open the app, and you will see a button labeled " Scan QR Code. " Click that button and scan the QR code; it will automatically build the Android app on your device.
  • For iOS users, simply scan the QR code using the Camera app .
  • If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.


Step 3: Start Coding

- Approach:

  • Generate a random number between a specified range (e.g., 1 to 20).
  • Allow the user to input their guess.
  • Provide feedback on whether the guess is too high, too low, or correct.
  • Display a congratulatory message when the user guesses the correct number, along with the total attempts made.

Let's dive into the code in detail.

Import libraries:

Import required libraries at the top of the file.

JavaScript
// Import necessary hooks from React
import { useState, useEffect } from "react";
// Import components from React Native
import {
    View,           // Container component for layout
    Text,           // For displaying text
    TextInput,      // For user input
    TouchableOpacity, // For button press
    StyleSheet,     // For styling components
} from "react-native";


StyleSheet:

Create a StyleSheet to style components like container, head, input, etc.

JavaScript
// Styles for the components
const styles = StyleSheet.create({
    container: {
        flex: 1, // Fill the screen
        alignItems: "center", // Center horizontally
        justifyContent: "center", // Center vertically
        backgroundColor: "#f2f2f2", // Light background
        padding: 16, // Padding around content
    },
    head: {
        fontWeight: "bold", // Bold text
        fontSize: 24, // Large font
        marginBottom: 20, // Space below
        color: "#333", // Dark text color
    },
    input: {
        padding: 10, // Padding inside input
        borderWidth: 1, // Border thickness
        borderColor: "#ccc", // Border color
        borderRadius: 10, // Rounded corners
        width: "80%", // Input width
        marginBottom: 20, // Space below
        backgroundColor: "#fff", // White background
        fontSize: 18, // Font size
    },
    button: {
        backgroundColor: "#007BFF", // Blue background
        borderRadius: 10, // Rounded corners
        paddingVertical: 12, // Vertical padding
        paddingHorizontal: 24, // Horizontal padding
    },
    buttonText: {
        color: "#fff", // White text
        fontSize: 18, // Font size
        fontWeight: "bold", // Bold text
    },
    result: {
        marginTop: 20, // Space above
        fontSize: 18, // Font size
        color: "#333", // Text color
        fontWeight: "bold", // Bold text
    },
});


Title Text:

This title explains what the app does. We use the text "Guess a Number between 1 to 20" to show that the app is to play Guess the Number Game.

JavaScript
{/* Title Text */}
<Text style={styles.head}>
    Guess Number between 1 to 20
</Text>


- TextInput:

This TextInput is used to get a number from the user. We will show what the user types using a state variable called "term." When you type or change the text in the TextInput component, we will use the handleChange function with the onChangeText prop to update the value.

JavaScript
// State to store user's guess input
const [term, setTerm] = useState("");

// Handler for input change
function handleChange(text) {
    setTerm(text); // Update input state
}

{/* Input for user's guess */}
<TextInput
    style={styles.input}
    placeholder="Enter your guess"
    onChangeText={handleChange}
    value={term}
    keyboardType="numeric"
/>


- Check Button:

This button is used to call the checkGuess function when the user taps on it. It is made with the TouchableOpacity component, which makes the Text component interactive for the user.

JavaScript
{/* Button to check guess */}
<TouchableOpacity
    style={styles.button}
    onPress={checkGuess}
>


- generateRandomNumber function:

Before we talk about the checkGuess function, let's look at the generateRandomNumber function. This function creates a random number between 1 and 20 using Math.floor and Math.random. It saves this number in the secretNum state variable. We use useState to set this up, and it generates and updates the number only once, when the app starts.

JavaScript
// State to store the secret random number (generated once)
const [secretNum] = useState(generateRandomNumber());

// Function to generate a random number between 1 and 20
function generateRandomNumber() {
    return Math.floor(Math.random() * 20) + 1;
}


- checkGuess function:

This function checks the number that a user inputs, called term, and compares it with a secret number called secretNum. It stores the result in a variable called newResult based on a few conditions:

  1. If the user does not enter any number (the input is an empty string), newResult will be set to "Enter Valid Input."
  2. If the number entered is not between 1 and 20, `newResult` will be set to "Enter a valid number between 1 and 20."
  3. If the number is between 1 and 20, the function compares it to `secretNum`:
    1. If the term is lower than secretNum , newResult is set to "Lower."
    2. If the term is higher than secretNum , newResult is set to "Higher."
    3. If the term is the same as secretNum , it assigns a message to newResult that says "Yippee, correct! It took you ${stepCount + 1} ${stepCount === 1 ? "step" : "steps"}." (For example: "Yippee, correct! It took you 4 steps.")

Finally, the function updates the state with the value of newResult using setResult on the result state variable, so the user can see the result directly.

JavaScript
// State to store result message
const [result, setResult] = useState("");
// State to count the number of guesses
const [stepCount, setStepCount] = useState(0);

// Function to check user's guess
function checkGuess() {
    let newResult = ""; // Temporary result message

    // If input is empty
    if (term === "") {
        newResult = "Enter Valid Input";
    }
    // If input is not a number or out of range
    else if (
        isNaN(term) ||
        parseInt(term) < 1 ||
        parseInt(term) > 20
    ) {
        newResult = "Enter a valid number between 1 and 20";
    } else {
        setStepCount(stepCount + 1); // Increment guess count

        // If guess is lower than secret number
        if (parseInt(term) < secretNum) {
            newResult = "Lower";
        }
        // If guess is higher than secret number
        else if (parseInt(term) > secretNum) {
            newResult = "Higher";
        }
        // If guess is correct
        else {
            newResult = `Yippee, correct! It took you ${stepCount + 1
                } ${stepCount === 1 ? "step" : "steps"}.`;
        }
    }

    setResult(newResult); // Update result message
}


- Display Result:

Show the result by putting the result state variable inside a Text Component. This variable should be updated by the checkGuess function.

JavaScript
// State to store result message
const [result, setResult] = useState("");

{/* Display result */}
<Text style={styles.result}>
    You Guessed: {result}
</Text>


Now, wrap all design code with a View component, return it from the App component, and place all methods and useStates within the App component. Ensure to export the App.

Complete Source Code

App.js:

App.js
// Import necessary hooks from React
import { useState, useEffect } from "react";
// Import components from React Native
import {
    View,           // Container component for layout
    Text,           // For displaying text
    TextInput,      // For user input
    TouchableOpacity, // For button press
    StyleSheet,     // For styling components
} from "react-native";

// Main App component
const App = () => {
    // State to store user's guess input
    const [term, setTerm] = useState("");
    // State to store result message
    const [result, setResult] = useState("");
    // State to store the secret random number (generated once)
    const [secretNum] = useState(generateRandomNumber());
    // State to count the number of guesses
    const [stepCount, setStepCount] = useState(0);

    // Effect to reset step count when secretNum changes
    useEffect(() => {
        setStepCount(0); // Reset guess count
    }, [secretNum]);

    // Function to generate a random number between 1 and 20
    function generateRandomNumber() {
        return Math.floor(Math.random() * 20) + 1;
    }

    // Handler for input change
    function handleChange(text) {
        setTerm(text); // Update input state
    }

    // Function to check user's guess
    function checkGuess() {
        let newResult = ""; // Temporary result message

        // If input is empty
        if (term === "") {
            newResult = "Enter Valid Input";
        }
        // If input is not a number or out of range
        else if (
            isNaN(term) ||
            parseInt(term) < 1 ||
            parseInt(term) > 20
        ) {
            newResult = "Enter a valid number between 1 and 20";
        } else {
            setStepCount(stepCount + 1); // Increment guess count

            // If guess is lower than secret number
            if (parseInt(term) < secretNum) {
                newResult = "Lower";
            }
            // If guess is higher than secret number
            else if (parseInt(term) > secretNum) {
                newResult = "Higher";
            }
            // If guess is correct
            else {
                newResult = `Yippee, correct! It took you ${stepCount + 1
                    } ${stepCount === 1 ? "step" : "steps"}.`;
            }
        }

        setResult(newResult); // Update result message
    }

    // Render UI
    return (
        <View style={styles.container}>
            {/* Heading */}
            <Text style={styles.head}>
                Guess Number between 1 to 20
            </Text>
            {/* Input for user's guess */}
            <TextInput
                style={styles.input}
                placeholder="Enter your guess"
                onChangeText={handleChange}
                value={term}
                keyboardType="numeric"
            />
            {/* Button to check guess */}
            <TouchableOpacity
                style={styles.button}
                onPress={checkGuess}
            >
                <Text style={styles.buttonText}>Check</Text>
            </TouchableOpacity>
            {/* Display result */}
            <Text style={styles.result}>
                You Guessed: {result}
            </Text>
        </View>
    );
};

// Styles for the components
const styles = StyleSheet.create({
    container: {
        flex: 1, // Fill the screen
        alignItems: "center", // Center horizontally
        justifyContent: "center", // Center vertically
        backgroundColor: "#f2f2f2", // Light background
        padding: 16, // Padding around content
    },
    head: {
        fontWeight: "bold", // Bold text
        fontSize: 24, // Large font
        marginBottom: 20, // Space below
        color: "#333", // Dark text color
    },
    input: {
        padding: 10, // Padding inside input
        borderWidth: 1, // Border thickness
        borderColor: "#ccc", // Border color
        borderRadius: 10, // Rounded corners
        width: "80%", // Input width
        marginBottom: 20, // Space below
        backgroundColor: "#fff", // White background
        fontSize: 18, // Font size
    },
    button: {
        backgroundColor: "#007BFF", // Blue background
        borderRadius: 10, // Rounded corners
        paddingVertical: 12, // Vertical padding
        paddingHorizontal: 24, // Horizontal padding
    },
    buttonText: {
        color: "#fff", // White text
        fontSize: 18, // Font size
        fontWeight: "bold", // Bold text
    },
    result: {
        marginTop: 20, // Space above
        fontSize: 18, // Font size
        color: "#333", // Text color
        fontWeight: "bold", // Bold text
    },
});

// Export the App component as default
export default App;

Output


Your Number Guessing App is now ready for users to enjoy! You can expand on this basic example by adding more features and enhancing the user interface.


Next Article

Similar Reads