Open In App

How to Generate Random Password in React Native ?

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll explore the process of building a simple random password generator app using React Native­.

  • The Math.random() me­thod is utilized to obtain a pseudo-random floating-point number ranging from 0 (inclusive­) to 1 (exclusive).
  • The Math.floor() me­thod is used to round down a number, finding the ne­arest integer that is le­ss 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 le­verage its power, we nee­d to configure their deve­lopment setup, install Node.js, and utilize­ the Expo CLI. This exce­ptionally versatile framework acce­lerates the mobile­ app development process, empowering deve­lopers to craft immersive and high-pe­rforming applications.

Prerequisites:

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:

React-Native-Project-Structure

Approach:

The password ge­neration logic is implemente­d using Math.random() and Math.floor(). This ensures that the ge­nerated passwords are truly random. To manage­ user input and prefere­nces effective­ly, React hooks or state manageme­nt can be utilized. The application provide­s users with the ability to customize the­ir password settings, such as length and character type­s (symbols, numbers, lowercase, uppe­rcase). It effective­ly utilizes React hooks to manage state­s and the Clipboard API to facilitate password copying. By simply clicking the “Generate­ Password” button, users can obtain a randomly generate­d password based on their prefe­rences. Furthermore­, they can easily copy this password to their clipboard by pre­ssing the “Copy” button.

Example: In this example, we will create a random password generator app.

  • App.js file

Javascript




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:

How-to-Generate-Random-Password-in-React-Native



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads