![]() |
VOOZH | about |
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.
Math.random().Math.floor().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-nameStart the server by using the following command.
npx expo startThen, the application will display a QR code.
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 required libraries at the top of the file.
- : Create a StyleSheet to style components like container, button, buttonText, etc.
-: This text provides clarity about the capabilities of the button below.
- : 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.
- : 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.
After updating the value of the randomNumber variable with new random number, we are displaying that using below code.
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.
App.js: