Open In App

How to Generate Random Numbers in React Native ?

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

Generating random numbers is a fundamental aspect of React Native development. It enables various functionalities like generating game elements, creating unique identifiers, and implementing randomized UI components. In this article, we are going to see how we can generate a random number by using React Native.

To generate random numbers in React Native, use `Math.random()` for a decimal value between 0 and 1. Combine it with `Math.floor()` to obtain whole numbers within a specified range.

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

Demo Video

Prerequisites

Approa​ch

  • Specify the range (min and max).
  • Generate a random decimal number (0-1) with Math.random().
  • Scale the number by multiplying it by the range difference.
  • Shift the number by adding the minimum value.
  • Round down to the nearest integer with Math.floor().
  • Store or use a random number.

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, 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

Example: In this example, the state initializes with a null randomNumber. Pressing the "Random Number" button triggers generateRandomNumber, generating a random number within a range. Updating the state triggers re-rendering. Basic styling is applied with StyleSheet.

- Import libraries: Import required libraries at the top of the file.

JavaScript
// Import useState hook from React and necessary components from react-native
import { useState } from 'react';
// Import core components from react-native for building UI
import {
    View,             // Container component for layout
    TouchableOpacity, // Button component that responds to touch
    Text,             // Component for displaying text
    StyleSheet        // Utility for creating styles
} from 'react-native';


- StyleSheet: Create a StyleSheet to style components like container, button, buttonText, etc.

JavaScript
// Define styles for the components
const styles = StyleSheet.create({
    container: {
        flex: 1, // Take full height
        justifyContent: 'center', // Center vertically
        alignItems: 'center', // Center horizontally
        padding: 20 // Add padding
    },
    button: {
        backgroundColor: 'green', // Button background color
        paddingHorizontal: 20, // Horizontal padding
        paddingVertical: 10, // Vertical padding
        borderRadius: 5, // Rounded corners
        marginBottom: 20, // Space below button
    },
    buttonText: {
        color: 'white', // Text color
        fontSize: 18, // Text size
        fontWeight: 'bold', // Bold text
    },
    randomNumber: {
        fontSize: 24, // Random number text size
        fontWeight: 'bold', // Bold text
        color: 'red', // Text color
    },
    heading: {
        fontSize: 20, // Heading text size
        marginBottom: 20, // Space below heading
        color: "green", // Heading text color
        fontWeight: 'bold', // Bold heading
    }
});


-Text above Button: This text provides clarity about the capabilities of the button below.

JavaScript
<Text style={styles.heading}>
    Geeksforgeeks || Generate Random Number In React Native
</Text>


- Random Number Button UI: Here is the code to create a button that shows "Random Number" on the screen. This button is made using a Text component, and it is wrapped in a TouchableOpacity component, which allows users to click it like a button. When the user taps the button, it calls the function called generateRandomNumber to get a random number.

JavaScript
<TouchableOpacity
    style={styles.button}
    onPress={generateRandomNumber}> {/* Button to generate random number */}
    <Text style={styles.buttonText}>
        Random Number
    </Text>
</TouchableOpacity>


- generateRandomNumber function: This function is used to generate a random number by using the Math.random() function and updating the state variable randomNumber by calling setRandomNumber useState with new random number.

JavaScript
// Declare a state variable to store the random number
const [randomNumber, setRandomNumber] = useState(null);

// Function to generate a random number between 1 and 100
const generateRandomNumber = () => {
    const min = 1; // Minimum value
    const max = 100; // Maximum value
    // Generate random number in the range [min, max]
    const number = Math.floor(Math.random() * (max - min + 1)) + min;
    setRandomNumber(number); // Update state with the new random number
};


After updating the value of the randomNumber variable with new random number, we are displaying that using below code.

JavaScript
{
// Conditionally render the random number if it exists
randomNumber !== null &&
<Text style={styles.randomNumber}>
    Number is: {randomNumber}
</Text>
}


Now, wrap the "Text above button", the "Random Number button", and the "Random Number text" inside a View component, and then return it from the App component. Also, ensure that the App component is exported.

Complete Source Code

App.js:

JavaScript
// Import useState hook from React and necessary components from react-native
import { useState } from 'react';
// Import core components from react-native for building UI
import {
    View,             // Container component for layout
    TouchableOpacity, // Button component that responds to touch
    Text,             // Component for displaying text
    StyleSheet        // Utility for creating styles
} from 'react-native';

// Define the main App component
const App = () => {

    // Declare a state variable to store the random number
    const [randomNumber, setRandomNumber] = useState(null);

    // Function to generate a random number between 1 and 100
    const generateRandomNumber = () => {
        const min = 1; // Minimum value
        const max = 100; // Maximum value
        // Generate random number in the range [min, max]
        const number = Math.floor(Math.random() * (max - min + 1)) + min;
        setRandomNumber(number); // Update state with the new random number
    };

    // Render the UI
    return (
        <View style={styles.container}> {/* Main container with styling */}
            <Text style={styles.heading}>
                Geeksforgeeks || Generate Random Number In React Native
            </Text>
            <TouchableOpacity
                style={styles.button}
                onPress={generateRandomNumber}> {/* Button to generate random number */}
                <Text style={styles.buttonText}>
                    Random Number
                </Text>
            </TouchableOpacity>
            {
                // Conditionally render the random number if it exists
                randomNumber !== null &&
                <Text style={styles.randomNumber}>
                    Number is: {randomNumber}
                </Text>
            }
        </View>
    );
};

// Define styles for the components
const styles = StyleSheet.create({
    container: {
        flex: 1, // Take full height
        justifyContent: 'center', // Center vertically
        alignItems: 'center', // Center horizontally
        padding: 20 // Add padding
    },
    button: {
        backgroundColor: 'green', // Button background color
        paddingHorizontal: 20, // Horizontal padding
        paddingVertical: 10, // Vertical padding
        borderRadius: 5, // Rounded corners
        marginBottom: 20, // Space below button
    },
    buttonText: {
        color: 'white', // Text color
        fontSize: 18, // Text size
        fontWeight: 'bold', // Bold text
    },
    randomNumber: {
        fontSize: 24, // Random number text size
        fontWeight: 'bold', // Bold text
        color: 'red', // Text color
    },
    heading: {
        fontSize: 20, // Heading text size
        marginBottom: 20, // Space below heading
        color: "green", // Heading text color
        fontWeight: 'bold', // Bold heading
    }
});

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

Output



Next Article

Similar Reads