Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Create a meme generator by using ReactJS
Next article icon

Build a Random Name Generator using ReactJS

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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

  • Introduction to React
  • React Components
  • ReactJS Hooks
  • NPM or NPX

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

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;  } 
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>  ); 

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:


Next Article
Create a meme generator by using ReactJS
author
saurabhkumarsharma05
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • React-Questions
  • Geeks Premier League 2023

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
    4 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 d
    3 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 acc
    4 min read
  • Create a meme generator by using ReactJS
    In this tutorial, we’ll create a meme generator using ReactJS. In the meme generator, we have two text fields in which we enter the first text and last text. After writing the text when we click the Gen button, it creates a meme with an image and the text written on it. Preview Image: PrerequisiteTh
    3 min read
  • Create a Random Quote Generator using React-Native
    React Native is the most flexible and powerful mobile application development framework, which has various features embedded into it. Using this framework, we can create different interactive applications. Creating a Random Quote Generator using React Native is one of the interactive project which u
    4 min read
  • Bill/Invoice Generator using React
    Bill/Invoice Generator website using React helps users easily make, customize, and print invoices and can add or delete items. It uses React's building blocks to make the design easy to update and reuse. The user also has a feature of downloading the pdf version of the generated bill Preview of fina
    5 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
    2 min read
  • Color Palette Generator app using React
    Color Palette Generator App using ReactJS is a web application which enables use­rs to effortlessly gene­rate random color palettes, vie­w the colors, and copy the color codes to the­ clipboard with just a single click. There is also a search bar which allows the user to check different color themes
    5 min read
  • Domain name finder using ReactJS
    In this article, we are going to make a domain name generator app that generates plenty of domain names related to our input keyword available to buy. In this domain name generator, we will take a text given by the user and will generate plenty of names related to the input text given, and by clicki
    4 min read
  • How to generate random colors by using React hooks ?
    In web development, colors play a vital role in creating visually appealing and engaging user interfaces. In React we may need to generate random colors dynamically. In this article, we will explore how to achieve this using React hooks, a powerful feature introduced in ReactJs. Pre-requisite:NPM
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences