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



Similar Reads

Build a Random User Generator App Using ReactJS
In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact information to simulate user data for testing and
4 min read
Build Random Quote Generator using VueJS
We are going to build a Random Quote Generator using Vue.js. This application will fetch random quotes from an API and display them on the screen. Users will have the option to copy the quote to their clipboard or generate a new random quote. Prerequisites:Node.jsVue.jsApproachWe'll create a Vue.js component called QuoteGenerator that fetches rando
4 min read
Flutter - Build a Random Quote Generator App
Flutter is a UI toolkit developed by Google back in 2007. It is the first choice of most beginner cross-platform developers because of its straightforward learning curve and simple syntax. Flutter provides a simple API to generate beautiful UI without a hassle. One can develop apps for many platforms including Android, iOS, Windows, Mac, Linux, etc
3 min read
Build a Random Number Generator in Tailwind CSS
A Random Number Generator (RNG) is a tool that generates a random number within a specified range. By combining Tailwind CSS's utility classes with JavaScript, you can create a simple and visually appealing RNG that can be easily integrated into any web application. Approach:Create an HTML file and include the necessary Tailwind CSS CDN link in the
2 min read
Random Quote Generator App using ReactJS
In this article, we will create an application that uses an API to generate random quotes. The user will be given a button which on click will fetch a random quote from the API and display it on the screen. Users can generate many advices by clicking the button again. The button and the quotes are displayed beautifully using CSS styling to create a
4 min read
Build a Captcha Generator Using ReactJs
A CAPTCHA generator is a tool that creates random and visually distorted text, requiring user input to prove they are human. It prevents automated bots from accessing websites or services by testing human comprehension. Our Captcha generator ge­nerates random text-base­d captchas that users must accurately input in order to process, effectively ens
4 min read
Flutter - How to Get App Name, Package Name, Version & Build number
In this article, we will learn about how to get package name, app name, version and build number and many more things in our Flutter app. The main usecase of using this is when we want to give a new update to users and have to notify them from our app. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Develo
2 min read
Random Quote Generator Using HTML, CSS and JavaScript
A Random Quote Generator is capable of pulling quotes randomly from an API, a database, or simply from an array. We will be designing a Random Quote Generator from scratch using HTML, CSS, JavaScript, and type.fit API. The webpage displays a random quote from a collection and upon the click of a button, it randomly generates a new quote. We will fi
8 min read
Random String Generator using JavaScript
JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments. In this article, we need to create a Random String Generator using Javascript that will ge
7 min read
Random Image Generator using JavaScript
In this article, we will learn how to generate random images in fixed intervals using only HTML, CSS, and JavaScript. Approach: The pictures which are going to be generated randomly on the website should be stored in the form of an array, these pictures are then displayed to the user within a regular time interval. We use the setInterval() function
4 min read