Home » How to Generate Random Password in React

How to Generate Random Password in React

how to generate random password react js

In this tutorial, we will learn how to create a random password generator using React JS. We will build a simple application that allows users to customize the password length and select different character types for the generated password, such as uppercase letters, lowercase letters, numbers, and symbols.

Generate Random Password in React JS

Step 1: Initializing State Variables

import React, { useState } from "react";

function App() {
  const [options, setOptions] = useState({
    length: 10,
    uppercase: false,
    lowercase: false,
    number: false,
    symbols: false,
    isError: false,
  });

  const [isError, setIsError] = useState(false);
  const [generatedPassword, setGeneratedPassword] = useState("");

  // Rest of the code
}

The options object represents the user’s selected options for generating the password. The generatedPassword variable will hold the final generated password.

Step 2: Implementing the Password Generation Logic

Now, we define the generateRandomPassword function, which is called when the “Generate Password” button is clicked. This function generates a random password based on the selected options.

const generateRandomPassword = () => {
    if (
      !options?.uppercase &&
      !options?.lowercase &&
      !options?.number &&
      !options?.symbols
    ) {
      setIsError(true);
      return;
    }

    setIsError(false);

    const uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
    const numberChars = "0123456789";
    const symbolChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~';

    let passwordChars = "";
    let password = "";

    if (options.uppercase) {
      passwordChars += uppercaseChars;
    }

    if (options.lowercase) {
      passwordChars += lowercaseChars;
    }

    if (options.number) {
      passwordChars += numberChars;
    }

    if (options.symbols) {
      passwordChars += symbolChars;
    }

    const passwordLength = options.length;

    for (let i = 0; i < passwordLength; i++) {
      const randomIndex = Math.floor(Math.random() * passwordChars.length);
      password += passwordChars[randomIndex];
    }

    setGeneratedPassword(password);
  };

In this code block, we first check if at least one option is selected (uppercase, lowercase, number, or symbols). If none of the options are selected, we set the isError state variable to true and display an error message.

Next, we have defined different character sets for uppercase letters, lowercase letters, numbers, and symbols. Based on the user’s selected options, we concatenate the respective character sets into the passwordChars string.

We then generate a random password by selecting random characters from the passwordChars string using a loop. The loop runs passwordLength times, and in each iteration, we generate a random index to retrieve a character from the passwordChars string.

Finally, we update the generatedPassword state variable with the generated password.

Step 3: Rendering the UI

  return (
    <div className="container">
      <div className="card">
        <div className="card-header">
          <p className="title">Generate Random Password</p>
        </div>


        <div className="card-body">
          <label>Password length</label>
          <input
            value={options.length}
            onChange={({ target }) => {
              setOptions({ ...options, length: target.value });
            }}
            name="confirmPassword"
            type="number"
            placeholder="Password length"
            min={4}
          />


          <div className="row">
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.uppercase}
                onChange={() => {
                  setOptions({ ...options, uppercase: !options.uppercase });
                }}
              />
              <label>Uppercase</label>
            </div>
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.lowercase}
                onChange={() => {
                  setOptions({ ...options, lowercase: !options.lowercase });
                }}
              />
              <label>Lowercase</label>
            </div>
          </div>


          <div className="row">
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.number}
                onChange={() => {
                  setOptions({ ...options, number: !options.number });
                }}
              />
              <label>Number</label>
            </div>


            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.symbols}
                onChange={() => {
                  setOptions({ ...options, symbols: !options.symbols });
                }}
              />
              <label>Symbols</label>
            </div>
          </div>


          {isError && (
            <span className="error">Please selete atleast one option</span>
          )}


          <button className="btn" onClick={generateRandomPassword}>
            Generate Password
          </button>
        </div>
      </div>


      {generatedPassword && (
        <div className="password">
          <label>Generated Password:</label>
          <p>{generatedPassword}</p>
        </div>
      )}
    </div>
  );

In the above code block, we defined the UI elements and their functionality as follows:

  1. Card Component: We wrap the UI components in a card component that displays the title and body of our application.
  1. Password Length Input: We add an input field for the user to specify the desired password length. The value of the input field is controlled by the options.length state variable.
  1. Checkbox Options: We provide checkboxes for the user to select different character types. Each checkbox corresponds to one of the options (uppercase, lowercase, number, and symbols). The checked state of the checkbox is controlled by the corresponding option in the options object.
  1. Error Handling: We display an error message if no character type is selected. The error message is shown conditionally based on the value of the isError state variable.
  1. Generate Password Button: We add a button that triggers the password generation process when clicked. When the button is clicked, the generateRandomPassword function is invoked.
  2. Displaying the Generated Password: If a password has been generated, we display it in the UI. The generated password is conditionally rendered if the generatedPassword state variable has a value.

Also check out:

Complete code of App.js:

import React, { useState } from "react";

function App() {
  const [options, setOptions] = useState({
    length: 10,
    uppercase: false,
    lowercase: false,
    number: false,
    symbols: false,
    isError: false,
  });

  const [isError, setIsError] = useState(false);
  const [generatedPassword, setGeneratedPassword] = useState("");

  const generateRandomPassword = () => {
    if (
      !options?.uppercase &&
      !options?.lowercase &&
      !options?.number &&
      !options?.symbols
    ) {
      setIsError(true);
      return;
    }

    setIsError(false);

    const uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
    const numberChars = "0123456789";
    const symbolChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~';

    let passwordChars = "";
    let password = "";

    if (options.uppercase) {
      passwordChars += uppercaseChars;
    }

    if (options.lowercase) {
      passwordChars += lowercaseChars;
    }

    if (options.number) {
      passwordChars += numberChars;
    }

    if (options.symbols) {
      passwordChars += symbolChars;
    }

    const passwordLength = options.length;

    for (let i = 0; i < passwordLength; i++) {
      const randomIndex = Math.floor(Math.random() * passwordChars.length);
      password += passwordChars[randomIndex];
    }

    setGeneratedPassword(password);
  };

  return (
    <div className="container">
      <div className="card">
        <div className="card-header">
          <p className="title">Generate Random Password</p>
        </div>

        <div className="card-body">
          <label>Password length</label>
          <input
            value={options.length}
            onChange={({ target }) => {
              setOptions({ ...options, length: target.value });
            }}
            name="confirmPassword"
            type="number"
            placeholder="Password length"
            min={4}
          />

          <div className="row">
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.uppercase}
                onChange={() => {
                  setOptions({ ...options, uppercase: !options.uppercase });
                }}
              />
              <label>Uppercase</label>
            </div>
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.lowercase}
                onChange={() => {
                  setOptions({ ...options, lowercase: !options.lowercase });
                }}
              />
              <label>Lowercase</label>
            </div>
          </div>

          <div className="row">
            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.number}
                onChange={() => {
                  setOptions({ ...options, number: !options.number });
                }}
              />
              <label>Number</label>
            </div>

            <div className="checkbox-container">
              <input
                type="checkbox"
                name="languages"
                checked={options.symbols}
                onChange={() => {
                  setOptions({ ...options, symbols: !options.symbols });
                }}
              />
              <label>Symbols</label>
            </div>
          </div>

          {isError && (
            <span className="error">Please selete atleast one option</span>
          )}

          <button className="btn" onClick={generateRandomPassword}>
            Generate Password
          </button>
        </div>
      </div>

      {generatedPassword && (
        <div className="password">
          <label>Generated Password:</label>
          <p>{generatedPassword}</p>
        </div>
      )}
    </div>
  );
}

export default App;

Output:

generate random password in react

Conclusion

In this blog post, we have explored how to generate a random password in React.js. We have handled the user input for password options and generated a random password based on the selected criteria. We have also implemented error handling to ensure that at least one character type is selected. Hope it was helpful.

Leave a Reply

Your email address will not be published.