Open In App

Build a Random Name Generator using ReactJS

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, a Random Name Ge­nerator will be created using React.js. Building a Random Name Generator means creating a program or application that generates random names, typically for various purposes like usernames, fictional characters, or data testing. It usually involves combining or selecting names from predefined lists or patterns.

Prerequisites

Steps to Create a React Application

Create a react application by using this command

npx create-react-app random-name-generator

After creating your project folder, i.e. random-name-generator, use the following command to navigate to it:

cd random-name-generator

Project Structure

The package.json file will look like:

{
"name": "random-name-generator",
"version": "0.0.0",
"private": true,
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"react-scripts": "latest"
}
}

Approach / Functionalities

The provide­d React.js code showcases a Random Name­ Generator, allowing users to dynamically ge­nerate and manipulate name­s.

  • Dynamic Name Generation: It allows users to generate and manipulate names using the generateRandomName function, which selects random first and last names from predefined lists.
  • Copying Generated Names: Users can easily copy the generated name to the clipboard using the copyToClipboard function.
  • Modifying Names: Users have the option to modify either the first or last name using the changeFirstName and changeLastName functions.
  • Real-time Updates: The app uses React’s useState for state management, ensuring real-time updates of the generated name as users interact with the interface.
  • User-Friendly Interface: The user interface provides a seamless experience for generating, copying, and modifying names, enhancing user interaction.

Example: Write the below code in App.js file and style.css in the src directory

Javascript




// App.js
import React, { useState } from 'react';
import './style.css';
  
const App = () => {
  
    // Generated name, copied status, and 
    // lists of first and last names must 
    // all be stored in state variables.
  
    const [generatedFirstName, setGeneratedFirstName] = useState('');
    const [generatedLastName, setGeneratedLastName] = useState('');
    const [copied, setCopied] = useState(false);
  
    // Lists of Indian first names and last names
    const firstNames = [
        'Aarav', 'Aditi', 'Akshay', 'Amit', 'Ananya',
        'Arjun', 'Avani', 'Bhavya', 'Chetan', 'Devi',
        'Divya', 'Gaurav', 'Isha', 'Kiran', 'Manoj',
        'Neha', 'Preeti', 'Rajesh', 'Riya', 'Shreya',
        'Varun', 'Saurabh', 'Ajay', 'Sandip', 'Sadan',
        'Jyoti', 'Sapna', 'Prem'
    ];
    const lastNames = [
        'Agarwal', 'Bansal', 'Chopra', 'Gupta', 'Jain',
        'Kapoor', 'Mehta', 'Patel', 'Rao', 'Sharma',
        'Singh', 'Trivedi', 'Verma', 'Yadav'
    ];
  
    //  To conjure up a name out of nowhere, use this function.
  
    const generate = () => {
        const randomFirstName =
            firstNames[Math.floor(Math.random() * firstNames.length)];
        const randomLastName =
            lastNames[Math.floor(Math.random() * lastNames.length)];
        setGeneratedFirstName(randomFirstName);
        setGeneratedLastName(randomLastName);
        setCopied(false);
    };
  
    //  The name generated can be copied to the 
    // clipboard with this function.
    const copy = () => {
        const fullName =
            `${generatedFirstName} ${generatedLastName}`;
        const textField =
            document.createElement('textarea');
        textField.innerText = fullName;
        document.body.appendChild(textField);
        textField.select();
        document.execCommand('copy');
        textField.remove();
        setCopied(true);
    };
  
    // Function to change the first name
    const changeFirstName = () => {
        const randomFirstName =
            firstNames[Math.floor(Math.random() * firstNames.length)];
        setGeneratedFirstName(randomFirstName);
        setCopied(false);
    };
  
    // Function to change the last name
    const changeLastName = () => {
        const randomLastName =
            lastNames[Math.floor(Math.random() * lastNames.length)];
        setGeneratedLastName(randomLastName);
        setCopied(false);
    };
  
    return (
        <div className="name-generator-container">
            <h1>
                Random Indian Name Generator
            </h1>
            <div className="buttons-container">
                <button className="generate-button"
                    onClick={generate}>
                    Generate Name
                </button>
                <button className="copy-button"
                    onClick={copy}>
                    Copy Name
                </button>
            </div>
            {copied && <p className="copy-success">
                Name Copied to Clipboard!
            </p>}
            <p className="generated-name">
                Generated Name:
                {`${generatedFirstName} ${generatedLastName}`}
            </p>
            <div className="buttons-container">
                <button className="change-button"
                    onClick={changeFirstName}>
                    Change First Name
                </button>
                <button className="change-button"
                    onClick={changeLastName}>
                    Change Last Name
                </button>
            </div>
        </div>
    );
};
  
export default App;


Javascript




// index.js
  
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
  
import App from './App';
  
const root = createRoot(document.getElementById('app'));
  
root.render(
    <StrictMode>
        <App />
    </StrictMode>
);


CSS




/* style.css */
  
.name-generator-container {
    text-align: center;
    margin: 20px auto;
    padding: 40px;
    border: 2px solid #3498db;
    border-radius: 10px;
    background-color: #f0f0f0;
    max-width: 600px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    transition: box-shadow 0.3s ease-in-out;
}
  
.name-generator-container:hover {
    box-shadow: 10px 10px 50px 10px grey;
}
  
h1 {
    font-size: 24px;
    color: #333;
    margin-bottom: 20px;
}
  
.buttons-container {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
}
  
.generate-button,
.copy-button,
.change-button {
    padding: 15px;
    font-size: 16px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
}
  
.generate-button:hover,
.copy-button:hover,
.change-button:hover {
    box-shadow: 0px 0px 15px 2px grey;
    transition: all ease-in-out 0.5s;
}
  
.generate-button {
    background: green;
    color: white;
}
  
.copy-button {
    color: white;
    background: crimson;
}
  
.change-button {
    background-color: #2980b9;
    color: white;
}
  
.generated-name {
    font-size: 22px;
    margin: 20px 0;
    font-weight: bold;
    font-family: 'Courier New', Courier, monospace;
}
  
.copy-success {
    color: #27ae60;
}
  
.center-buttons {
    display: flex;
    justify-content: center;
}
  
@media (max-width: 768px) {
    .name-generator-container {
        max-width: 90%;
    }
}
  
/* Animation on copy button click */
@keyframes copySuccessAnimation {
    0% {
        transform: translateY(-10px);
        opacity: 0;
    }
  
    100% {
        transform: translateY(0);
        opacity: 1;
    }
}
  
.copy-success-animation {
    animation: copySuccessAnimation 0.5s ease-in-out;
}


Steps to run the Application: Type the following command in the terminal:

npm start

Type the following URL in the browser:

http://localhost:3000/

Output:

Build-a-Random-Name-Generator-Using-ReactJs



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads