How to Generate Random Password in React Native ?
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.
React Native is a highly popular platform known for its ability to create native mobile apps for both iOS and Android using just one codebase. To leverage its power, we need to configure their development setup, install Node.js, and utilize the Expo CLI. This exceptionally versatile framework accelerates the mobile app development process, empowering developers to craft immersive and high-performing applications.
Prerequisites:
- Introduction to React Native
- React Native Components
- React useState
- React hooks
- Expo CLI
- Node.js and npm (Node Package Manager)
Steps to Create React Native Application
Step 1: Create React Native Application With Expo CLI
Run the following command to start a new “PasswordGenerator” React Native project:
npx create-expo-app PasswordGenerator
Step 2: Change the directory to the project folder:
cd PasswordGenerator
Project Structure:
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.
Example: In this example, we will create a random password generator app.
- App.js file
import React, { useState } from 'react';
import {
View, Text, TextInput,
TouchableOpacity,
StyleSheet,
Clipboard, Switch
} from 'react-native';
const styles = StyleSheet.create({
container: {
margin: 20,
marginTop: 100,
padding: 20,
borderColor: '#ccc',
borderRadius: 8,
borderWidth: 1,
shadowColor: 'grey',
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 1,
shadowRadius: 10,
elevation: 5,
backgroundColor: '#fff',
},
header: {
color: 'green',
textAlign: 'center',
fontSize: 30,
marginBottom: 10,
},
subHeader: {
textAlign: 'center',
fontSize: 18,
marginBottom: 10,
},
inputContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
},
label: {
flex: 1,
fontSize: 18,
},
input: {
flex: 2,
padding: 10,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
fontSize: 16,
},
checkboxLabel: {
fontSize: 20,
},
button: {
padding: 13,
backgroundColor: '#007bff',
color: '#fff',
borderRadius: 5,
overflow: 'hidden',
textAlign: 'center',
fontSize: 16,
fontWeight: 'bold',
margin: 15,
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
copyButton: {
marginLeft: 10,
backgroundColor: '#007bff',
color: '#fff',
borderRadius: 5,
overflow: 'hidden',
padding: 10,
fontSize: 14,
},
successMessage: {
color: 'green',
textAlign: 'center',
fontSize: 20,
},
});
const App = () => {
// Define states for the app
const [password, setPassword] = useState('');
const [passwordLength, setPasswordLength] = useState('12');
const [useSymbols, setUseSymbols] = useState(true);
const [useNumbers, setUseNumbers] = useState(true);
const [useLowerCase, setUseLowerCase] = useState(true);
const [useUpperCase, setUseUpperCase] = useState(true);
const [successMessage, setSuccessMessage] = useState('');
// Generates random password based on user preferences
const generatePassword = () => {
let charset = '';
let newPassword = '';
if (useSymbols) charset += '!@#$%^&*()';
if (useNumbers) charset += '0123456789';
if (useLowerCase) charset += 'abcdefghijklmnopqrstuvwxyz';
if (useUpperCase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (let i = 0; i < parseInt(passwordLength); i++) {
newPassword +=
charset.charAt(Math.floor(
Math.random() * charset.length));
}
setPassword(newPassword);
};
// Function to copy password to clipboard.
const copyToClipboard = () => {
Clipboard.setString(password);
setSuccessMessage('Password copied to clipboard!');
setTimeout(() => setSuccessMessage(''), 2000);
};
return (
<View style={styles.container}>
<Text style={styles.header}>
Geeksforgeeks
</Text>
<Text style={styles.subHeader}>
Random Password Generator
</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>
Password Length:
</Text>
<TextInput
keyboardType="numeric"
value={passwordLength}
onChangeText={(text) => setPasswordLength(text)}
style={styles.input}
/>
</View>
<View style={styles.checkbox}>
<Switch
value={useSymbols}
onValueChange={() => setUseSymbols(!useSymbols)}
/>
<Text style={styles.checkboxLabel}>
Symbols
</Text>
</View>
<View style={styles.checkbox}>
<Switch
value={useNumbers}
onValueChange={() => setUseNumbers(!useNumbers)}
/>
<Text style={styles.checkboxLabel}>
Numbers
</Text>
</View>
<View style={styles.checkbox}>
<Switch
value={useLowerCase}
onValueChange={() => setUseLowerCase(!useLowerCase)}
/>
<Text style={styles.checkboxLabel}>
LowerCase
</Text>
</View>
<View style={styles.checkbox}>
<Switch
value={useUpperCase}
onValueChange={() => setUseUpperCase(!useUpperCase)}
/>
<Text style={styles.checkboxLabel}>UpperCase</Text>
</View>
<TouchableOpacity style={styles.button}
onPress={generatePassword}>
<Text style={styles.buttonText}>
Generate Password
</Text>
</TouchableOpacity>
{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>
)}
{successMessage !== '' &&
<Text style={styles.successMessage}>
{successMessage}
</Text>}
</View>
);
};
export default App;
Step 5: To run the React native application, open the command prompt or terminal and enter the command listed below.
npx expo start
To run on Android:
npx react-native run-android
To run on Ios:
npx react-native run-ios
Output: