How to build a password generator in React

In today’s world, having security is integral for many different reasons. One of the reasons include having protection against cyber threats such as hacking, identity thefts, data breaches etc. Another reason is to ensure personal privacy by safeguarding information like financial data and personal records. Therefore, as programmers, it is vital to know how to create secure passwords via a password generator to provide security for the reasons mentioned above.

Step-by-step procedure

In this section, we will go through the main steps of building a React app that allows users to specify the length of a password they need, resulting in a random password containing a mix of alphanumeric characters and special symbols being created.

Step 1: Creating a React app

In case we don’t have a React app set up on our systems, we create one by executing the commands below, one after the other:

npx create-react-app password-gen
cd password-gen

Note: In the place of the folder name password-gen, we can write a folder name of our choice.

Step 2: Creating a password generator component

Next, we will create a React component responsible for the main functionality of generating passwords. The code for this is shown here:

import React, { useState } from 'react';
// Defining the PasswordGenerator component as a functional component
const PasswordGenerator = () => {
// Defining state variables for 'password' and 'length' using the 'useState' hook
const [password, setPassword] = useState(''); // the 'password' constant stores the generated password
const [length, setLength] = useState(12); // the 'length' constant stores the desired password length, initialized to 12
// Defining a function to generate a new password
const generatePassword = () => {
// Defining a character set that includes lowercase letters, uppercase letters, numbers, and special characters
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+';
// Initialize an empty string to store the generated password
let newPassword = '';
//Generating a password of the specified length by iterating through a for loop
for (let i = 0; i < length; i++) {
// Generating a random index within the character set length
const randomIndex = Math.floor(Math.random() * charset.length);
// Appending a random character from the character set to the password
newPassword += charset[randomIndex];
}
// Setting the generated password in the 'password' state variable
setPassword(newPassword);
};
// Render the component's UI inside the return method
return (
<div className="password-generator">
<h1>Password Generator</h1>
<div>
<label>Password Length:</label>
<input
type="number"
value={length}
onChange={(e) => setLength(e.target.value)}
min={1}
/>
</div>
<button onClick={generatePassword}>Generate Password</button>
<div>
<label>Generated Password:</label>
<input type="text" value={password} readOnly />
</div>
</div>
);
};
export default PasswordGenerator;

Here, the component includes a generatePassword function to create random passwords based on the specified length and character set. After that, the component’s UI is rendered to enter the password length in an input field, a button to trigger password generation, and an input field to display the generated password of the specified length.

Step 3: Importing the password generator component

Now, we must make sure that the password generator component is integrated into the main App component of the React app for the app to run successfully.

import React from 'react';
import './App.css';
import PasswordGenerator from './PasswordGenerator';
function App() {
//PasswordGenerator component stored within <div> tags for better organization of code
return (
<div className="App">
<PasswordGenerator />
</div>
);
}
export default App;

Finally, we run the React app by using the npm start command.

Code output

After incorporating all of the steps above, we can run the code below to see the expected output. Run it to see it in action!

import React from 'react';
import './App.css';
import PasswordGenerator from './PasswordGenerator';

function App() {
  //PasswordGenerator component stored within <div> tags for better organization of code
  return (
    <div className="App">
      <PasswordGenerator />
    </div>
  );
}

export default App;
A password generator in React

Conclusion

Overall, this password generator provides a viable solution for generating strong and secure passwords by demonstrating the fundamental principles of building a React app consisting of component creation, state management, and user input handling. In addition, it serves as a solid foundation for more advanced password generators, which can be made by adding additional features such as password strength indicators and copy-to-clipboard functionality.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved