Random Password Generator using ReactJS easily

0
188

Creating a password generator is a great way to practice your React skills while developing a useful tool. In this blog post, we will walk through building a simple yet functional password generator component using React. We’ll cover the entire process from setting up the component state to generating and copying passwords. Let’s dive in!

Introduction

Passwords are essential for security, but creating them can sometimes be a hassle. What if you could generate secure passwords with just a few clicks? That’s what we’ll achieve with our React Password Generator. This tool will allow users to generate passwords of customizable length and complexity, including options for uppercase letters, lowercase letters, digits, special characters, and similar characters.

Follow this video for complete guidance

Setting Up the Component

First, let’s outline the structure of our component. We need to handle several states and user interactions:

  • State Management: We’ll use React’s useState to manage the password, length, and various character inclusion options.
  • Event Handlers: We need functions to update state based on user inputs.
  • Password Generation: A function to generate the password based on current settings.
  • Copy to Clipboard: A function to copy the generated password to the clipboard.

Implementing the Password Generator

Here’s how the component is structured:

import { useEffect, useState } from "react";

export default function Password() {
    const [password, setPassword] = useState('12345678');
    const [length, setLength] = useState(8);
    const [capital, setCapital] = useState(true);
    const [small, setSmall] = useState(true);
    const [digit, setDigit] = useState(true);
    const [special, setSpecial] = useState(true);
    const [similar, setSimilar] = useState(true);

    const changeLength = (event) => {
        setLength(event.target.value);
    };
    const changeCapital = () => {
        setCapital(!capital);
    };
    const changeSmall = () => {
        setSmall(!small);
    };
    const changeDigit = () => {
        setDigit(!digit);
    };
    const changeSpecial = () => {
        setSpecial(!special);
    };
    const changeSimilar = () => {
        setSimilar(!similar);
    };

    const generatePassword = () => {
        let pass = '';
        let chars = '';
        if (capital) chars += 'ABCDEFGHJKLMNOPQRSTUVWXYZ';
        if (small) chars += 'abcdefghijkmnopqrstuvwxyz';
        if (digit) chars += '123456789';
        if (special) chars += '~!@#$%^&*()_+';
        if (similar) chars += '0OlI';

        for (let i = 1; i <= length; i++) {
            let random_index = Math.floor(Math.random() * chars.length);
            pass += chars[random_index];
        }
        setPassword(pass);
    };

    const copyPassword = () => {
        navigator.clipboard.writeText(password);
        alert('Copied password to clipboard');
    };

    useEffect(() => {
        generatePassword();
    }, [length, capital, small, special, digit, similar]);

    return (
        <>
            <div className="container mt-5 py-3 px-1 bg-success text-white">
                <h1 className="text-center">Password Generator</h1>
                <hr />
                <div className="row px-5">
                    <div className="col-10">
                        <h3>{password}</h3>
                    </div>
                    <div className="col-2">
                        <span onClick={copyPassword} className="btn btn-primary">Copy Password</span>
                    </div>
                </div>
                <hr />
                <div className="row">
                    <div className="col-12">
                        <div className="px-5">
                            <label>Length ({length})</label>
                            <input onChange={changeLength} value={length} className="w-100" type="range" min="5" max="32" />
                        </div>
                    </div>
                </div>
                <div className="row mt-4 px-5">
                    <div className="col">
                        <input onChange={changeCapital} id="capital" type="checkbox" checked={capital} />
                        <label htmlFor="capital">[A-Z]</label>
                    </div>
                    <div className="col">
                        <input onChange={changeSmall} id="small" type="checkbox" checked={small} />
                        <label htmlFor="small">[a-z]</label>
                    </div>
                    <div className="col">
                        <input onChange={changeDigit} id="digit" type="checkbox" checked={digit} />
                        <label htmlFor="digit">[0-9]</label>
                    </div>
                    <div className="col">
                        <input onChange={changeSpecial} id="special" type="checkbox" checked={special} />
                        <label htmlFor="special">[!@#$%^&*()_+]</label>
                    </div>
                    <div className="col">
                        <input onChange={changeSimilar} id="similar" type="checkbox" checked={similar} />
                        <label htmlFor="similar">[Il, 0O]</label>
                    </div>
                </div>
            </div>
        </>
    )
}

Explanation

  1. State Variables:
    • password: Stores the generated password.
    • length: Defines the length of the password.
    • capital, small, digit, special, similar: Toggle options for including various character types.
  2. Event Handlers:
    • Each change function updates its respective state. For checkboxes, toggling the state on change suffices.
  3. Password Generation:
    • We concatenate character sets based on user preferences and generate a password of the specified length by randomly selecting characters from the combined set.
  4. Copy to Clipboard:
    • Utilizes the Clipboard API to copy the password to the clipboard and provides user feedback with an alert.
  5. UseEffect Hook:
    • The useEffect hook triggers password regeneration whenever any of the settings change.
ALSO READ  Creating a Random Quote Generator Using ReactJS

This password generator is a functional React component that demonstrates state management, user input handling, and side effects. By following this guide, you should have a good understanding of how to build and customize similar components in React.

Feel free to tweak the design, add more features, or style it further to fit your needs. Happy coding!

Comments are closed.