How to Generate Random Number in React Native?

04-Apr-2023

.

Admin

How to Generate Random Number in React Native?

Hi Guys,

In this tutorial, I will show you react native generate random number example. if you have question about how to generate random number in react native then I will give simple example with solution. This tutorial will give you simple example of random number using react native. step by step explain how to get random number in react native. you will do the following things for how to implement random number in 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