React Native Generate Random Number Example

Jun 11, 2022 . Admin

Hi Guys,

Today, I will let you know example of how to get random number in react native. We will use how to implement random number in react native . This post will give you simple example of react native generate random number example. I explained simply about how to generate random number in react native. So, let's follow few step to create example of random number using react native.

In this example javascript Math.floor() and Math.random() function is used.The Math.floor() function is used to round the given number to its downward integer value. The Math.random() function is used to Generate Random Number to any range in Point Float value. So we would use both Math.floor() and Math.random() function together to generate random number between given range.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

const App = () => {
    const [number, setNumber] = React.useState(1);

    const getRandomNumber = () => {
        const randomNumber = Math.floor(Math.random() * 100) + 1;
        setNumber(randomNumber);
    }

    return (
        <View style={styles.container}>
            <View style={styles.innerContainer}>
                <View style={styles.numberContainer}>
                    <Text style={styles.text}>{number}</Text>
                </View>
                <Button
                    title='get random number'
                    onPress={() => getRandomNumber()}
                />
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    innerContainer: {
        padding:80,
        borderRadius:30,
        backgroundColor:'red',
    },
    numberContainer: {
        alignItems:'center',
        marginBottom: 10,
    },
    text: {
        fontSize:25,
        color:'white',
        fontWeight:'700',
    },
});

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...

#React Native