How to build a random password generator in react js (react js project for beginners)

Random password generator project in react js.
React js Project demo (what we are going to build)

Hi, welcome here in this tutorial we are going to develop a random password generator in React Js, The prerequisites for this project are as follows:

  • Node.js should be installed in your system
  • Create a brand new ReactJs project. Just copy the code below:
npx create-react-app my-app
JavaScript

The brand-new project should look like this:

brand new react js project

Now Here is your code for the app.js file copy it and paste it into the app.js:

import logo from './logo.svg';
import './App.css';
import Checkbox from './components/Checkbox';
import { useState } from 'react';

function App(props) {

  const [passwordGen, setPasswordGen] = useState({
    length: 5,
    uppercase: false,
    lowercase: false,
    numbers: false,
    symbols: false
  })

  const [handelText, setHandelText] = useState('');
  const [copied, setCopied] = useState(false)

  const handleChangeUpperCase = () => {
    setPasswordGen({
      ...passwordGen,
      uppercase: !passwordGen.uppercase,
    });
  }

  const handleChangeLowerCase = () => {
    setPasswordGen({
      ...passwordGen,
      lowercase: !passwordGen.lowercase,
    });
  }

  const handleChangeNumbers = () => {
    setPasswordGen({
      ...passwordGen,
      numbers: !passwordGen.numbers,
    });
  }

  const handleChangeSymbols = () => {
    setPasswordGen({
      ...passwordGen,
      symbols: !passwordGen.symbols,
    });
  }

  const setPasswordLength = (val) => {
    setPasswordGen({
      ...passwordGen,
      length: val,
    });
  }

  function generatePassword() {
    const numbersArray = [1,2,3,4,5,6,7,8,9,0];
    const symbolsArray = ['!', '@', '#', '%', '^', '&', '*', '(', ')', ]

    const characterCodes = Array.from(Array(26)).map((_e, i) => i + 97);
    const lowerCaseLetters = characterCodes.map((code) => String.fromCharCode(code));
    const upperCaseLetters = characterCodes.map((code) => String.fromCharCode(code));
    const { length, uppercase, lowercase, numbers, symbols } = passwordGen;

    const generateTheWord = (
      length, 
      uppercase, 
      lowercase, 
      numbers, 
      symbols
    ) => {
      const availableCharacters = [
        ...(lowercase ? lowerCaseLetters : []),
        ...(uppercase ? upperCaseLetters : []),
        ...(numbers ? numbersArray : []),
        ...(symbols ? symbolsArray : []),
      ];
      const shuffleArray = (array) => array.sort(()=> Math.random() - 0.5);
      const characters = shuffleArray(availableCharacters).slice(0, length);
      setHandelText(characters.join(''));
      return characters
    };

    generateTheWord(length, uppercase, lowercase, numbers, symbols);
  }

  return (
    <div className='wrapper'>
      <div className='container wrapper-box'>
        <h2>Password Generator</h2>
        <div className='password-box'>
          <input 
          type="text"
          placeholder=''
          autoComplete='off'
          value={handelText}
          onChange={(e)=> setHandelText(e.target.value)}
          />

          <button
          className='copy-button'
          onClick={()=> {
            if(handelText.length > 0){
              navigator.clipboard.writeText(handelText);
              setCopied(true);
              setInterval(() => {
                setCopied(false);
              }, 2000);
            }
          }}
          > { copied ? 'Copied!' : 'Copy Text'}</button>


        </div>
        <br></br>

        <div className='word-crieteria__box'>
          <div>
            <label>Password Length</label>
          </div>
          <div>
            <input
            type="number"
            min="8"
            max="16"
            value={passwordGen.length}
            onChange = {(e) => setPasswordLength(e.target.value)}
            />
          </div>
        </div>

        <div className='word-crieteria__box'>
          <div>
            <label>Uppercase letters</label>
          </div>
          <div>
            <Checkbox 
            value={passwordGen.uppercase}
            onChange={handleChangeUpperCase}
            />
          </div>
        </div>

        <div className='word-crieteria__box'>
          <div>
            <label>Lowercase letters</label>
          </div>
          <div>
            <Checkbox 
            value={passwordGen.lowercase}
            onChange={handleChangeLowerCase}
            />
          </div>
        </div>

        <div className='word-crieteria__box'>
          <div>
            <label>Include Numbers</label>
          </div>
          <div>
            <Checkbox 
            value={passwordGen.numbers}
            onChange={handleChangeNumbers}
            />
          </div>
        </div>

        <div className='word-crieteria__box'>
          <div>
            <label>Include Symbols</label>
          </div>
          <div>
            <Checkbox 
            value={passwordGen.symbols}
            onChange={handleChangeSymbols}
            />
          </div>
        </div>

        <button className='generate-button' onClick={generatePassword}>
          Generate Password
        </button>


      </div>
    </div>
  );
}

export default App;
JavaScript

Here is your code for the app.css file

:root {
  --primary: rgb(24, 128, 226);
  --secondary: rgb(2, 23, 54);
}

body {
  margin: 0;
  color: #ffffffcb;
}



.wrapper {
  /* background-color: rgb(250, 250, 250); */
  background-color: var(--primary);
  height: 100vh;
  display: flex;
  align-items: center;
}

div#root {
  height: 100vh;
  margin: 0;
  padding: 0;
}

.container {
  background-color: var(--secondary);
  width: 400px;
  max-width: 100%;
  margin: 0 auto;
  outline: 2px solid rgb(224, 224, 224);
  border-radius: 10px;
  box-shadow: 0px 0px 70px 0px rgba(0, 0, 0, 0.664);
}

.wrapper-box {
  padding: 30px;
}

.word-crieteria__box {
  display: flex;
  justify-content: space-between;
  padding: 10px 0px;
}

.generate-button {
  margin-top: 30px;
  width: 100%;
  height: 50px;
  border: 0px;
  cursor: pointer;
  border-radius: 5px;
  background-color: var(--primary);
  color: #ffffffcb;
  font-size: 16px;
  font-weight: bolder;
}

.password-box {
  display: flex;
  justify-content: space-between;
}

.password-box > input[type='text'] {
  width: 70%;
  height: 35px;
  margin-right: 10px;
  font-size: 16px;
  padding-left: 10px;
  color: #000;
  letter-spacing: 2px;
}

button.copy-button {
  display: block;
  width: 25%;
  cursor: pointer;
  border: 0px;
  font-size: 14px;
  font-weight: bolder;
  border-radius: 5px;
  background-color: var(--primary);
  color: #ffffffcb;
}

.word-crieteria__box input[type='checkbox'] {
  width: 20px;
  height: 20px;
  color: black;
}

.word-crieteria__box label {
  font-weight: 500;
}

input[type='number'] {
  width: 60px;
  height: 20px;
}
CSS

Create a folder in src and name the folder ‘components’ and then make a new file in it. The name for the file should be ‘Checkbox.jsx’.

The code for the Checkbox.jsx is as follows:

import React from 'react'

const Checkbox = (props) => {
    const { value, onChange} = props
  return (
    <>
    <input
    type="checkbox"
    className="checkbox"
    onChange = {onChange}
    checked = {value}
    />
    </>
  )
}

export default Checkbox
JavaScript

After writing the code into the editor you can run the command below:

npm run start
JavaScript

Here is a complete tutorial on building password generating app in react js.