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 Jokes Generator App using React-Native
Next article icon

Color Palette Generator app using React

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 for their specified color.

Preview of Finla Output:

gfg-(9)

Prerequisitesa and Technologies Used:

  • React
  • CSS
  • Class Components in React

Approach:

  • The ge­nerateColorPalette­ method creates a random color pale­tte by performing iterations base­d on the maxColorBoxes value, which is set to 21. During each iteration, it ge­nerates random hex color code­s and adds them to an array called colorList, which reside­s within the component's state.
  • On the­ other hand, copyColorToClipboard function serves the­ purpose of accepting a hexValue­ and an index as inputs. It makes use of the­ navigator.clipboard.writeText method to copy the­ provided hexValue to the­ clipboard.
  • Upon successful completion, it updates the­ copiedColorIndex in the state­ with the current index value­. Consequently, it highlights the copie­d color and displays a message stating "Copied" to provide­ visual feedback.
  • Each block consists of a colored re­ctangle represe­nting a specific shade, followed by its corre­sponding hex code. Additionally, when clicking on any give­n block, an event handler invoke­s copyColorToClipboard function to facilitate copying that particular code.
  • Lastly, a "Refresh Palette" button triggers the generateColorPalette method when clicked, generating a fresh set of random colors.

Steps to Create the project:

Step 1: Create a react application by using this command

npx create-react-app colorPaletteGenerator

Step 2: After creating your project folder, i.e. colorPaletteGenerator, use the following command to navigate to it:

cd colorPaletteGenerator

Project Structure:

The updated dependencies in package.json file will look like

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

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

CSS
/* App.css */  * {     margin: 0;     padding: 0;     box-sizing: border-box; }  .container {     margin: 20px;     display: flex;     justify-content: center;     flex-wrap: wrap; }  .container .color {     margin: 12px;     padding: 7px;     list-style: none;     cursor: pointer;     text-align: center;     background: #fff;     border-radius: 16px;     box-shadow: 0 0px 30px 0px rgb(207, 206, 206);     transition: all 0.3s ease; }  h1 {     text-align: center;     padding: 10px;     color: green; }  .container .color:active {     transform: scale(0.95); }  .color .rect-box {     width: 185px;     height: 188px;     border-radius: 10px; }  .color:hover .rect-box {     filter: brightness(107%); }  .color .hex-value {     display: block;     color: #444;     user-select: none;     font-weight: 500;     font-size: 1.15rem;     margin: 12px 0 8px;     text-transform: uppercase; }  .refresh-btn {     position: fixed;     left: 50%;     bottom: 40px;     color: #fff;     cursor: pointer;     outline: none;     font-weight: 500;     font-size: 1.1rem;     border-radius: 5px;     background: green;     padding: 13px 20px;     border: none;     transform: translateX(-50%);     box-shadow: 0 0px 30px 0px grey;     transition: all 0.3s ease; }  .refresh-btn:hover {     background: rgb(4, 95, 4); }  .copied-message {     margin: 10px;     color: crimson;     font-weight: bold;     font-family: 'Courier New', Courier, monospace; }  .search-container {     position: relative;     margin: 20px auto;     width: 300px; }  .search-input {     width: 100%;     padding: 15px;     border: 2px solid #ccc;     border-radius: 15px;     font-size: 16px;     outline: none;     transition: border-color 0.3s;     box-shadow: 0 0px 10px 0px #b3b2b2; }  .search-input:hover {     border-color: #007bff; }  @media screen and (max-width: 500px) {     .container {         margin: 10px;     }      .container .color {         margin: 8px;         padding: 5px;         width: calc(100% / 2 - 20px);     }      .color .rect-box {         width: 100%;         height: 148px;     }      .color .hex-value {         font-size: 1.05rem;     }      .refresh-btn {         font-size: 1rem;     } } 
JavaScript
// App.js import React, { Component } from "react"; import "./App.css";  class App extends Component {     constructor() {         super();         this.state = {             colorList: [],             copiedColorIndex: null,             searchInput: "",             matchingColors: [], // Store matching colors         };     }      componentDidMount() {         this.generateColorPalette();     }      generateColorPalette = () => {         const maxColorBoxes = 21;         const colorList = [];          for (let i = 0; i < maxColorBoxes; i++) {             const randomHexColor = `#${Math.floor(Math.random() * 0xffffff)                 .toString(16)                 .padStart(6, "0")}`;             colorList.push(randomHexColor);         }          this.setState({ colorList, copiedColorIndex: null });     };      copyColorToClipboard = (hexValue, index) => {         navigator.clipboard             .writeText(hexValue)             .then(() => {                 this.setState({ copiedColorIndex: index });             })             .catch(() => {                 alert("Failed to copy the color code!");             });     };      handleSearchChange = (e) => {         const searchInput = e.target.value.toLowerCase();          // Color mapping with arrays of related colors         const colorMapping = {             red: ["#FF0000", "#FF5733", "#c21919", "#FF6347", "#FF4500"],             green: ["#00FF00", "#33FF73", "#C3FF00", "#228B22", "#008000"],             blue: ["#0000FF", "#3373FF", "#00C3FF", "#1E90FF", "#4169E1"],             yellow: ["#FFFF00", "#FFD700", "#FFEA00", "#F0E68C", "#FFAC33"],             pink: ["#FFC0CB", "#FF69B4", "#FF1493", "#FF6EB4", "#FF82AB"],             purple: ["#800080", "#9932CC", "#8A2BE2", "#A020F0", "#8000FF"],             orange: ["#FFA500", "#FFD700", "#FF8C00", "#FF7F50", "#FF4500"],             brown: ["#A52A2A", "#8B4513", "#D2691E", "#CD853F", "#DEB887"],             cyan: ["#00FFFF", "#20B2AA", "#40E0D0", "#00CED1", "#00C5CD"],             magenta: ["#FF00FF", "#FF69B4", "#DA70D6", "#BA55D3", "#FFA0B4"],             teal: ["#008080", "#008B8B", "#00FFFF", "#20B2AA", "#40E0D0"],             navy: ["#000080", "#00008B", "#0000FF", "#4169E1", "#0000CD"],             lime: ["#00FF00", "#32CD32", "#7FFF00", "#00FA9A", "#00FF7F"],             maroon: ["#800000", "#8B0000", "#B22222", "#A52A2A", "#800000"],             olive: ["#808000", "#6B8E23", "#556B2F", "#8FBC8B", "#9ACD32"],             silver: ["#C0C0C0", "#D3D3D3", "#DCDCDC", "#BEBEBE", "#A9A9A9"],             black: ["#000000", "#080808", "#121212", "#1C1C1C", "#262626"],             white: ["#FFFFFF", "#F5F5F5", "#FAFAFA", "#E0E0E0", "#D3D3D3"],             // Add more color mappings as needed         };          // Check if the search input matches any color name         const matchingColors = colorMapping[searchInput] || [];          this.setState({ searchInput, matchingColors });     };      render() {         const filteredColorList =             this.state.matchingColors.length > 0                 ? this.state.matchingColors                 : this.state.colorList;          return (             <div>                 <h1>Color Palette Generator</h1>                 <div className="search-container">                     <input                         type="text"                         className="search-input"                         placeholder="Search for a color"                         value={this.state.searchInput}                         onChange={this.handleSearchChange}                     />                 </div>                  {/* Render matching colors */}                 <ul className="container">                     {filteredColorList.map((hexValue, index) => (                         <li                             className="color"                             key={index}                             onClick={() =>                                 this.copyColorToClipboard(hexValue, index)                             }                         >                             <div                                 className="rect-box"                                 style={{ background: hexValue }}                             ></div>                             <span className="hex-value">                                 {hexValue}                                 {this.state.copiedColorIndex === index && (                                     <p className="copied-message">Copied</p>                                 )}                             </span>                         </li>                     ))}                 </ul>                  <button                     className="refresh-btn"                     onClick={this.generateColorPalette}                 >                     Refresh Palette                 </button>             </div>         );     } }  export default App; 

Steps to run the Application:

Step 1:Type the following command in the terminal:

npm start

Step 2: Type the following URL in the browser:

 http://localhost:3000/

Output:


Next Article
Create Jokes Generator App using React-Native
author
saurabhkumarsharma05
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Web Development Projects
  • ReactJS-Projects
  • Geeks Premier League 2023

Similar Reads

  • Create Memes Generator App using React-Native
    The Me­me Generator App is a mobile­ application that allows users to effortlessly create memes. With its use­r-friendly interface, use­rs can choose from a wide collection of popular me­me templates and add their own customized text to the top and bottom. In this article, we will see how we can bui
    4 min read
  • Create Jokes Generator App using React-Native
    In this article, we are going to build a jokes generator app using react native. React Native enables you to master the­ designing an elegant and dynamic use­r interface while e­ffortlessly retrieving joke­s from external APIs. Let's take a look at how our completed project will look Prerequisites /
    3 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 QR code generator app using ReactJS
    In this article, we will create a simple QR Code generator app. A QR code is a two-dimensional barcode that can be read by smartphones. It allows the encoding of more than 4,000 characters in a compact format. QR codes can be used for various purposes, such as displaying text to users, opening URLs,
    3 min read
  • Color Pallete Generator using JavaScript
    Color Palette Generator App using HTML CSS and JavaScript is a web application that 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 that allows the user to check differen
    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 Random Name Generator using ReactJS
    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 selec
    4 min read
  • 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
  • Build a Box Shadow Generator Using React JS
    In this article, We will create a box shadow generator using React Js. The application enables customization of various aspects of a box shadow, including position, size, color, opacity, and whether it should be inset or outset. Preview of final output: Let us have a look at how the final output wil
    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