Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created December 18, 2022 11:42
Show Gist options
  • Save leonidkuznetsov18/859cda1db26907610804b6f869aaac4f to your computer and use it in GitHub Desktop.
Save leonidkuznetsov18/859cda1db26907610804b6f869aaac4f to your computer and use it in GitHub Desktop.
React password generator
import React, { useState } from 'react';
function PasswordGenerator() {
const [password, setPassword] = useState('');
const [length, setLength] = useState(8);
const [includeSpecialCharacters, setIncludeSpecialCharacters] = useState(true);
const [easyToRead, setEasyToRead] = useState(true);
const [easyToSay, setEasyToSay] = useState(true);
function generatePassword() {
let newPassword = '';
let characterSet = easyToRead ? 'abcdefghijklmnopqrstuvwxyz' : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (includeSpecialCharacters) {
characterSet += '!@#$%^&*()';
}
if (easyToSay) {
characterSet += '2345679'; // Exclude characters that are hard to distinguish when spoken
}
for (let i = 0; i < length; i++) {
newPassword += characterSet.charAt(Math.floor(Math.random() * characterSet.length));
}
setPassword(newPassword);
}
return (
<div>
<label htmlFor="length">Length:</label>
<input type="number" value={length} onChange={(e) => setLength(e.target.value)} />
<br />
<label htmlFor="includeSpecialCharacters">Include special characters:</label>
<input type="checkbox" checked={includeSpecialCharacters} onChange={(e) => setIncludeSpecialCharacters(e.target.checked)} />
<br />
<label htmlFor="easyToRead">Easy to read:</label>
<input type="checkbox" checked={easyToRead} onChange={(e) => setEasyToRead(e.target.checked)} />
<br />
<label htmlFor="easyToSay">Easy to say:</label>
<input type="checkbox" checked={easyToSay} onChange={(e) => setEasyToSay(e.target.checked)} />
<br />
<button type="button" onClick={generatePassword}>Generate password</button>
<br /><label htmlFor="password">Password:</label>
<input type="text" value={password} readOnly />
</div>
);
}
export default PasswordGenerator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment