How to Generate Random Password in React Native ?
Last Updated :
25 May, 2025
In this article, we'll explore the process of building a simple random password generator app using React Native.
- The Math.random() method is utilized to obtain a pseudo-random floating-point number ranging from 0 (inclusive) to 1 (exclusive).
- The Math.floor() method is used to round down a number, finding the nearest integer that is less than or equal to the given value and removing any decimal fraction.
To give you a better idea of what we’re going to create, let’s watch a demo video.
Demo Video
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:
The password generation logic is implemented using Math.random() and Math.floor(). This ensures that the generated passwords are truly random. To manage user input and preferences effectively, React hooks or state management can be utilized. The application provides users with the ability to customize their password settings, such as length and character types (symbols, numbers, lowercase, uppercase). It effectively utilizes React hooks to manage states and the Clipboard API to facilitate password copying. By simply clicking the "Generate Password" button, users can obtain a randomly generated password based on their preferences. Furthermore, they can easily copy this password to their clipboard by pressing the "Copy" button.
- Import libraries: Import required libraries at the top of the file.
JavaScript
// Import necessary hooks and components from React and React Native
import { useState } from 'react';
import {
View, // Container component for layout
Text, // For displaying text
TextInput, // For user input fields
TouchableOpacity, // For clickable buttons
StyleSheet, // For styling components
Clipboard, // For copying text to clipboard
Switch // For toggle switches
} from 'react-native';
- StyleSheet: Create a StyleSheet to style components like container, header, subHeader, etc.
JavaScript
// Styles for the components
const styles = StyleSheet.create({
container: {
margin: 20, // Outer margin
marginTop: 100, // Top margin
padding: 20, // Inner padding
borderColor: '#ccc', // Border color
borderRadius: 8, // Rounded corners
borderWidth: 1, // Border width
shadowColor: 'grey', // Shadow color
shadowOffset: { width: 0, height: 0 }, // Shadow offset
shadowOpacity: 1, // Shadow opacity
shadowRadius: 10, // Shadow radius
elevation: 5, // Android shadow
backgroundColor: '#fff', // Background color
},
header: {
color: 'green', // Text color
textAlign: 'center', // Centered text
fontSize: 30, // Font size
marginBottom: 10, // Bottom margin
},
subHeader: {
textAlign: 'center', // Centered text
fontSize: 18, // Font size
marginBottom: 10, // Bottom margin
},
inputContainer: {
flexDirection: 'row', // Horizontal layout
alignItems: 'center', // Vertically center items
marginBottom: 10, // Bottom margin
},
label: {
flex: 1, // Take up 1 part of available space
fontSize: 18, // Font size
},
input: {
flex: 2, // Take up 2 parts of available space
padding: 10, // Inner padding
borderWidth: 1, // Border width
borderColor: '#ccc', // Border color
borderRadius: 8, // Rounded corners
fontSize: 16, // Font size
},
checkboxLabel: {
fontSize: 20, // Font size
},
button: {
padding: 13, // Inner padding
backgroundColor: '#007bff', // Button background color
color: '#fff', // Text color
borderRadius: 5, // Rounded corners
overflow: 'hidden', // Hide overflow
textAlign: 'center', // Centered text
fontSize: 16, // Font size
fontWeight: 'bold', // Bold text
margin: 15, // Margin
},
buttonText: {
color: '#fff', // Text color
fontSize: 16, // Font size
fontWeight: 'bold', // Bold text
},
copyButton: {
marginLeft: 10, // Left margin
backgroundColor: '#007bff', // Button background color
color: '#fff', // Text color
borderRadius: 5, // Rounded corners
overflow: 'hidden', // Hide overflow
padding: 10, // Inner padding
fontSize: 14, // Font size
},
successMessage: {
color: 'green', // Text color
textAlign: 'center', // Centered text
fontSize: 20, // Font size
},
});
Develop UI
- Title & Subtitle: Here is the code to display the title and subtitle of the app using a Text component, which conveys who is providing the app (for ex: "Geeksforgeeks") and its purpose (for ex: "Random Password Generator").
JavaScript
{/* App Title */}
<Text style={styles.header}>
Geeksforgeeks
</Text>
{/* Sub-Title */}
<Text style={styles.subHeader}>
Random Password Generator
</Text>
- Password Length TextInput: The Below code is for getting the password length from the user. It uses a TextInput component where the user can type the length, and a Text component that says "Password Length" to explain what the TextInput is for. Both the Text and TextInput are inside a View component. The passwordLength state variable is linked to the TextInput, so when the user types a number, it updates the passwordLength value using setPasswordLength from useState. We set the default value of passwordLength to "12," so when the app starts, the user will see "12" displayed.
JavaScript
// State to store the desired password length (as string for TextInput)
const [passwordLength, setPasswordLength] = useState('12');
{/* Input for password length */}
<View style={styles.inputContainer}>
<Text style={styles.label}>
Password Length:
</Text>
<TextInput
keyboardType="numeric" // Only allow numeric input
value={passwordLength} // Bind to passwordLength state
onChangeText={(text) => setPasswordLength(text)} // Update state on change
style={styles.input}
/>
</View>
- Switches: We are adding four switches to our user interface: Symbols, Numbers, LowerCase, and UpperCase. These switches allow users to choose whether they want to include them in their password or not. We used a Switch component for the switching function and a Text component to explain what each switch does. both are wrapped in a View component to hold them together.
By default, all the switches are set to true, meaning they are on. We have state variables like useSymbols, useNumbers, useLowerCase, and useUpperCase assigned for value prop for each switch respectively. When a user taps a switch, we update the state using functions like setUseSymbols, setUseNumbers, setUseLowerCase, and setUseUpperCase. These functions are connected to the onValueChange prop of each switch respectively.
JavaScript
// State to determine if symbols should be included
const [useSymbols, setUseSymbols] = useState(true);
// State to determine if numbers should be included
const [useNumbers, setUseNumbers] = useState(true);
// State to determine if lowercase letters should be included
const [useLowerCase, setUseLowerCase] = useState(true);
// State to determine if uppercase letters should be included
const [useUpperCase, setUseUpperCase] = useState(true);
{/* Switch for including symbols */}
<View style={styles.checkbox}>
<Switch
value={useSymbols} // Bind to useSymbols state
onValueChange={() => setUseSymbols(!useSymbols)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
Symbols
</Text>
</View>
{/* Switch for including numbers */}
<View style={styles.checkbox}>
<Switch
value={useNumbers} // Bind to useNumbers state
onValueChange={() => setUseNumbers(!useNumbers)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
Numbers
</Text>
</View>
{/* Switch for including lowercase letters */}
<View style={styles.checkbox}>
<Switch
value={useLowerCase} // Bind to useLowerCase state
onValueChange={() => setUseLowerCase(!useLowerCase)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
LowerCase
</Text>
</View>
{/* Switch for including uppercase letters */}
<View style={styles.checkbox}>
<Switch
value={useUpperCase} // Bind to useUpperCase state
onValueChange={() => setUseUpperCase(!useUpperCase)} // Toggle state
/>
<Text style={styles.checkboxLabel}>UpperCase</Text>
</View>
- Generate Password Button: This button is used to generate a password, designed by wrapping a Text component of some text like "Generate Password" with TouchableOpacity component to make the text acts like a button and when user taps on it, it will call generatePassword function.
JavaScript
{/* Button to generate password */}
<TouchableOpacity style={styles.button}
onPress={generatePassword}>
<Text style={styles.buttonText}>
Generate Password
</Text>
</TouchableOpacity>
- generatePassword: This function is designed to generate a password using certain choices. It checks if you want to include Symbols, Numbers, LowerCase, and UpperCase. If these options are selected, the function will add them to the password. It then uses Math.random and Math.floor to generate a new password randomly. Finally, it updates the password state variable with the new password using the setPassword useState function. By default, the password state variable starts as an empty string using useState.
JavaScript
// State to store the generated password
const [password, setPassword] = useState('');
// Function to generate a random password based on user preferences
const generatePassword = () => {
let charset = ''; // Initialize character set
let newPassword = ''; // Initialize new password string
// Add symbols to charset if selected
if (useSymbols) charset += '!@#$%^&*()';
// Add numbers to charset if selected
if (useNumbers) charset += '0123456789';
// Add lowercase letters to charset if selected
if (useLowerCase) charset += 'abcdefghijklmnopqrstuvwxyz';
// Add uppercase letters to charset if selected
if (useUpperCase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Loop to generate password of desired length
for (let i = 0; i < parseInt(passwordLength); i++) {
// Append a random character from charset to newPassword
newPassword +=
charset.charAt(Math.floor(
Math.random() * charset.length));
}
// Update password state with the newly generated password
setPassword(newPassword);
};
- Generated Password UI: The program will show a generated password using the password state variable, as long as it is not empty. It uses a Text component to display the password. Besides the password, there is a Copy button made with a TouchableOpacity component. When the user taps this button, it calls the copyToClipboard function to copy the password.
JavaScript
{/* Display generated password and copy button if password exists */}
{password !== '' && (
<View style={styles.inputContainer}>
<Text style={styles.label}>
Generated Password:
</Text>
<TextInput value={password}
style={styles.input} />
<TouchableOpacity style={styles.copyButton}
onPress={copyToClipboard}>
<Text style={styles.buttonText}>
Copy
</Text>
</TouchableOpacity>
</View>
)}
- copyToClipboard: This function copies the generated password to the clipboard. It uses the setString method from the Clipboard component. Then, it updates the SuccessMessage state variable to say, "Password copied to clipboard!" This lets the user know that the password has been copied successfully. We also show this message below the generated password using a Text component.
JavaScript
// State to store the success message after copying password
const [successMessage, setSuccessMessage] = useState('');
// Function to copy the generated password to clipboard
const copyToClipboard = () => {
Clipboard.setString(password); // Copy password to clipboard
setSuccessMessage('Password copied to clipboard!'); // Show success message
setTimeout(() => setSuccessMessage(''), 2000); // Hide message after 2 seconds
};
// This code will placed below the generated Passwrod.
{/* Show success message if present */}
{successMessage !== '' &&
<Text style={styles.successMessage}>
{successMessage}
</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 and components from React and React Native
import { useState } from 'react';
import {
View, // Container component for layout
Text, // For displaying text
TextInput, // For user input fields
TouchableOpacity, // For clickable buttons
StyleSheet, // For styling components
Clipboard, // For copying text to clipboard
Switch // For toggle switches
} from 'react-native';
// Main App component
const App = () => {
// State to store the generated password
const [password, setPassword] = useState('');
// State to store the desired password length (as string for TextInput)
const [passwordLength, setPasswordLength] = useState('12');
// State to determine if symbols should be included
const [useSymbols, setUseSymbols] = useState(true);
// State to determine if numbers should be included
const [useNumbers, setUseNumbers] = useState(true);
// State to determine if lowercase letters should be included
const [useLowerCase, setUseLowerCase] = useState(true);
// State to determine if uppercase letters should be included
const [useUpperCase, setUseUpperCase] = useState(true);
// State to store the success message after copying password
const [successMessage, setSuccessMessage] = useState('');
// Function to generate a random password based on user preferences
const generatePassword = () => {
let charset = ''; // Initialize character set
let newPassword = ''; // Initialize new password string
// Add symbols to charset if selected
if (useSymbols) charset += '!@#$%^&*()';
// Add numbers to charset if selected
if (useNumbers) charset += '0123456789';
// Add lowercase letters to charset if selected
if (useLowerCase) charset += 'abcdefghijklmnopqrstuvwxyz';
// Add uppercase letters to charset if selected
if (useUpperCase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Loop to generate password of desired length
for (let i = 0; i < parseInt(passwordLength); i++) {
// Append a random character from charset to newPassword
newPassword +=
charset.charAt(Math.floor(
Math.random() * charset.length));
}
// Update password state with the newly generated password
setPassword(newPassword);
};
// Function to copy the generated password to clipboard
const copyToClipboard = () => {
Clipboard.setString(password); // Copy password to clipboard
setSuccessMessage('Password copied to clipboard!'); // Show success message
setTimeout(() => setSuccessMessage(''), 2000); // Hide message after 2 seconds
};
// Render the UI
return (
<View style={styles.container}>
{/* App header */}
<Text style={styles.header}>
Geeksforgeeks
</Text>
{/* Sub-header */}
<Text style={styles.subHeader}>
Random Password Generator
</Text>
{/* Input for password length */}
<View style={styles.inputContainer}>
<Text style={styles.label}>
Password Length:
</Text>
<TextInput
keyboardType="numeric" // Only allow numeric input
value={passwordLength} // Bind to passwordLength state
onChangeText={(text) => setPasswordLength(text)} // Update state on change
style={styles.input}
/>
</View>
{/* Switch for including symbols */}
<View style={styles.checkbox}>
<Switch
value={useSymbols} // Bind to useSymbols state
onValueChange={() => setUseSymbols(!useSymbols)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
Symbols
</Text>
</View>
{/* Switch for including numbers */}
<View style={styles.checkbox}>
<Switch
value={useNumbers} // Bind to useNumbers state
onValueChange={() => setUseNumbers(!useNumbers)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
Numbers
</Text>
</View>
{/* Switch for including lowercase letters */}
<View style={styles.checkbox}>
<Switch
value={useLowerCase} // Bind to useLowerCase state
onValueChange={() => setUseLowerCase(!useLowerCase)} // Toggle state
/>
<Text style={styles.checkboxLabel}>
LowerCase
</Text>
</View>
{/* Switch for including uppercase letters */}
<View style={styles.checkbox}>
<Switch
value={useUpperCase} // Bind to useUpperCase state
onValueChange={() => setUseUpperCase(!useUpperCase)} // Toggle state
/>
<Text style={styles.checkboxLabel}>UpperCase</Text>
</View>
{/* Button to generate password */}
<TouchableOpacity style={styles.button}
onPress={generatePassword}>
<Text style={styles.buttonText}>
Generate Password
</Text>
</TouchableOpacity>
{/* Display generated password and copy button if password exists */}
{password !== '' && (
<View style={styles.inputContainer}>
<Text style={styles.label}>
Generated Password:
</Text>
<TextInput value={password}
style={styles.input} />
<TouchableOpacity style={styles.copyButton}
onPress={copyToClipboard}>
<Text style={styles.buttonText}>
Copy
</Text>
</TouchableOpacity>
</View>
)}
{/* Show success message if present */}
{successMessage !== '' &&
<Text style={styles.successMessage}>
{successMessage}
</Text>}
</View>
);
};
// Styles for the components
const styles = StyleSheet.create({
container: {
margin: 20, // Outer margin
marginTop: 100, // Top margin
padding: 20, // Inner padding
borderColor: '#ccc', // Border color
borderRadius: 8, // Rounded corners
borderWidth: 1, // Border width
shadowColor: 'grey', // Shadow color
shadowOffset: { width: 0, height: 0 }, // Shadow offset
shadowOpacity: 1, // Shadow opacity
shadowRadius: 10, // Shadow radius
elevation: 5, // Android shadow
backgroundColor: '#fff', // Background color
},
header: {
color: 'green', // Text color
textAlign: 'center', // Centered text
fontSize: 30, // Font size
marginBottom: 10, // Bottom margin
},
subHeader: {
textAlign: 'center', // Centered text
fontSize: 18, // Font size
marginBottom: 10, // Bottom margin
},
inputContainer: {
flexDirection: 'row', // Horizontal layout
alignItems: 'center', // Vertically center items
marginBottom: 10, // Bottom margin
},
label: {
flex: 1, // Take up 1 part of available space
fontSize: 18, // Font size
},
input: {
flex: 2, // Take up 2 parts of available space
padding: 10, // Inner padding
borderWidth: 1, // Border width
borderColor: '#ccc', // Border color
borderRadius: 8, // Rounded corners
fontSize: 16, // Font size
},
checkboxLabel: {
fontSize: 20, // Font size
},
button: {
padding: 13, // Inner padding
backgroundColor: '#007bff', // Button background color
color: '#fff', // Text color
borderRadius: 5, // Rounded corners
overflow: 'hidden', // Hide overflow
textAlign: 'center', // Centered text
fontSize: 16, // Font size
fontWeight: 'bold', // Bold text
margin: 15, // Margin
},
buttonText: {
color: '#fff', // Text color
fontSize: 16, // Font size
fontWeight: 'bold', // Bold text
},
copyButton: {
marginLeft: 10, // Left margin
backgroundColor: '#007bff', // Button background color
color: '#fff', // Text color
borderRadius: 5, // Rounded corners
overflow: 'hidden', // Hide overflow
padding: 10, // Inner padding
fontSize: 14, // Font size
},
successMessage: {
color: 'green', // Text color
textAlign: 'center', // Centered text
fontSize: 20, // Font size
},
});
// Export the App component as default
export default App;
Output
Similar Reads
React Native Tutorial React Native is a framework developed by Facebook for creating native-style applications for Android & iOS under one common language, i.e. JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can
5 min read
Introduction to React Native If you want to build mobile apps for both Android and iOS. What should you learn? The individual native languages for each app i.e, Java for Android and Swift/Objective-C for iOS?, Actually NO. Native Android and iOS development are quite different and can be expensive â first, the language itself i
3 min read
What are the steps to create first React Native App ? React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, etc. Weâre always looking for shorter development cycles, quicker time to deployment, and better app performance. And there are so many hybrid mobile
4 min read
Axios in React Native Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API.Axios in React NativeAxios is a library that helps you send HTTP requests in React Native apps. It allows mobile devices to communicate with a server, enabling them to send an
8 min read
Top React Native Apps to Build in 2025 Top React Native Apps to Build in 2025 is a popular framework for building high-performance mobile apps using JavaScript and React. It allows developers to create apps for both iOS and Android with a single codebase, saving time and resources. React Native, developed by Facebook. Initially, for iOS,
9 min read
How React Native works React Native is a popular framework for building mobile applications using JavaScript and React. It allows developers to write code once in JavaScript and run it on both Android and iOS devices, bridging the gap between web and native mobile development. In this article, weâll explore the main compo
5 min read
React Native FlatList Component FlatList is a React Native component that is a scrolling list that shows changing information while keeping the same look. It's great for long lists where the number of items can change. Instead of loading all items simultaneously, this component only shows what you can see on the screen. This makes
4 min read
How React Native is different from ReactJS ? In this article, we will learn about how React Native is different from ReactJS. Both are popular JavaScript libraries. ReactJS is primarily used for building user interfaces on the web, while React Native extends its capabilities to mobile app development.React JSIt is a JavaScript library that sup
4 min read
What is a bridge in React Native ? A React Native app comprises two sides as given below.The JavaScript SideThe Native SideThe Native Side should be Java or Kotlin for Android and Swift or Objective-C for iOS.The huge reason for the popularity of React Native is that a bridge can be created between the JavaScript code and Native lang
7 min read
What react-native :app:installDebug FAILED ? In this article we are going to fix this error i.e. if you are a react native developer then it's a big possibility that you might come across this error. Let's understand a solution that works wonders for this error. When does this error occur?This error occurs when we try to run our react-native p
2 min read