Open In App

How to Generate Random Password in React Native ?

Last Updated : 25 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
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.
How-to--Generate---Random--Password_


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 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.


- 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



Next Article

Similar Reads