DEV Community

Cover image for Random Password Generator with Reactjs
Kartik Budhraja
Kartik Budhraja

Posted on

Random Password Generator with Reactjs

Introduction:

We’ll walk through how to create a password generator app with React. The app will enable users to create strong passwords with various combinations of characters, including uppercase and lowercase letters, symbols, and numbers. It’ll also have an indicator to help gauge the strength of the user’s chosen password.

Follow - Linkedin

Project Features

~ Customizable Passwords: Generate highly secure passwords tailored to your specifications. Customize the length of your password, and choose to include uppercase and lowercase letters, numbers, and symbols.

~ Error Handling and Feedback: Experience user-friendly error handling and feedback mechanisms. The application provides real-time validation, ensuring that your selected options align with industry best practices for password security.

~ Effortless Copy-Paste Functionality: Simplify the process of securing your accounts with a built-in copy button. Generated passwords can be instantly copied to your clipboard with a single click. No more manual typing or memorization required – enhance your online security effortlessly.

Let's break down the code step by step and explain each concept used in the provided React application.

Step 1: Importing Dependencies
In this step, the necessary dependencies are imported. React is imported to create React components, and useState and useEffect are hooks provided by React to manage state and side-effects respectively. The styles.css file contains the CSS styles for the application.

import React, { useState, useEffect } from "react";
import "./styles.css";
Enter fullscreen mode Exit fullscreen mode

Step 2: Functional Component Definition
In this step, a functional React component named App is defined. The useState hook is used to create state variables for managing the password, password length, and options to include uppercase letters, lowercase letters, numbers, and symbols in the generated password. The errors state variable is used to handle error messages.

export default function App() {
  // State variables using useState hook
  const [password, setPassword] = useState("");
  const [passwordLength, setPasswordLength] = useState(15);
  const [uppercase, setUppercase] = useState(true);
  const [lowercase, setLowercase] = useState(true);
  const [numbers, setNumbers] = useState(true);
  const [symbols, setSymbols] = useState(true);
  const [errors, setErrors] = useState({});
Enter fullscreen mode Exit fullscreen mode

Step 3: Password Generation Logic
The generatePassword function is responsible for generating the password based on user preferences. It checks the selected options and password length and generates a password accordingly. If there are errors in the user input, appropriate error messages are set using the setErrors function.

const generatePassword = () => {
    setErrors({});
    if (!uppercase && !lowercase && !numbers && !symbols) {
      return setErrors("sdfsfsd");
    } else if (passwordLength === "0") {
      return setErrors("Password length cannot be 0");
    } else if (passwordLength === "") {
      return setErrors("Invalid password length");
    } else if (passwordLength >= 30) {
      setPassword("");
      return setErrors("Password length cannot exceed 30 characters");
    }

    let password = "";
    for (let i = 0; i < passwordLength; i++) {
      let choice = random(0, 3);
      if (lowercase && choice === 0) {
        password += randomLower();
      } else if (uppercase && choice === 1) {
        password += randomUpper();
      } else if (symbols && choice === 2) {
        password += randomSymbol();
      } else if (numbers && choice === 3) {
        password += random(0, 9);
      } else {
        i--;
      }
    }
    setPassword(password);
  };
Enter fullscreen mode Exit fullscreen mode

Step 4: Randomization Functions

These functions are helper functions used by the generatePassword function. random generates a random number within a specified range, randomLower and randomUpper generate random lowercase and uppercase letters respectively, and randomSymbol generates a random symbol from a predefined set of symbols.

const random = (min = 0, max = 1) => {
  // Function to generate a random number between min and max (inclusive)
  // ...
};

const randomLower = () => {
  // Function to generate a random lowercase letter
  // ...
};

const randomUpper = () => {
  // Function to generate a random uppercase letter
  // ...
};

const randomSymbol = () => {
  // Function to generate a random symbol
  // ...
};
Enter fullscreen mode Exit fullscreen mode

Step 5: useEffect Hook
The useEffect hook is used to generate a password when the component is mounted. It runs the generatePassword function once, initializing the password based on the default preferences.

useEffect(() => {
  // useEffect hook to generate a password when the component is mounted
  generatePassword();
}, []);
Enter fullscreen mode Exit fullscreen mode

Step 6: User Interface (JSX)

The return statement contains the JSX code representing the user interface of the application. It includes input fields for password length and checkboxes for selecting options (uppercase letters, lowercase letters, numbers, and symbols). The generated password is displayed along with a copy button. Error messages are displayed if there are any validation errors.

return (
  // JSX code for the user interface
  // ...
);
Enter fullscreen mode Exit fullscreen mode

Here is the reference of the working code


Conclusion:

That's a step-by-step explanation of the provided React code, covering the key concepts of React components, state management with hooks, password generation logic, and the useEffect hook for handling side-effects.

Follow Me on Social Media!
If you found this article helpful, feel free to connect with me on LinkedIn and Twitter for more programming tips and tutorials. Let's learn and grow together!

LinkedIn: https://www.linkedin.com/in/kartikbudhraja/

Top comments (0)