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 Random Quote Generator using React-Native
Next article icon

How to generate random colors by using React hooks ?

Last Updated : 09 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 & Node.js
  • React.js
  • React Hooks

Approach:

To generate random colors by using the React hook we will be creating a random color generator custom hook, here we will make a function to generate color according to user input. Adding an event handler with a button to change the color of our window.

Steps to Create React Application:

Step 1: Go to your command prompt and write the below command to create a react app.

npx create-react-app <YOUR_APP_NAME>

Step 2: Then go to your app folder by typing the below command

cd <YOUR_APP_NAME>

Project Structure:

Folder structure

Example: This example implements a custom hook to generate random color and render it as the background color.

Javascript

// Filename - App.js
 
import "./App.css";
import useGenerateRandomColor from "./useGenerateRandomColor";
 
function App() {
    const { color, generateColor } =
        useGenerateRandomColor();
    return (
        <div
            style={{
                height: "100vh",
                width: "100vw",
                backgroundColor: "#" + color,
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
            }}
        >
            <button
                style={{
                    padding: "40px",
                    borderRadius: "10px",
                    backgroundImage:
                        "linear-gradient(to top, #a8edea 0%, #fed6e3 100%)",
                    fontSize: "larger",
                }}
                onClick={generateColor}
            >
                Generate random color
            </button>
        </div>
    );
}
 
export default App;
                      
                       

Javascript

// Filename - useGenerateRandomColor.js
 
import { useState } from 'react';
 
const useGenerateRandomColor = () => {
    const [color, setColor] = useState("")
    const generateColor = () => {
        setColor(Math.random().toString(16).substr(-6));
    };
    return { color, generateColor };
 
};
export default useGenerateRandomColor;
                      
                       

Step to run the application: Run the following command to start your app in your localhost:3000.

npm start


Output: This output will be visible on the http:// localhost:3000 on the browser window.



Next Article
Create a Random Quote Generator using React-Native
author
megha25
Improve
Article Tags :
  • Misc
  • ReactJS
  • Web Technologies
  • React-Hooks
  • React-Questions
Practice Tags :
  • Misc

Similar Reads

  • How to create a Color-Box App using ReactJS?
    Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev
    5 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
  • 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
  • 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
  • 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
  • Create a Random Joke using React app through API
    In this tutorial, we'll make a website that fetches data (joke) from an external API and displays it on the screen. We'll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React f
    3 min read
  • How to generate QR-Code using 'react-qr-code' in ReactJS ?
    react-qr-code is a module or package for react that provides the QRCode component to generate the code with custom values. QR code is a square grid that can easily be readable with digital devices like smartphones. Prerequisites:NPM & Node.jsReact JSApproachTo generate QR code in react js we wil
    2 min read
  • How to build a Tic-Tac-Toe Game using React Hooks ?
    To build a Tic-Tac-Toe using react Hooks include the interactive components that represent the board, the signs, and at last the winner of the game. Preview of final output: Let us have a look at how the final application will look like. Prerequisite of Tic-Tac-Toe Game:Introduction to ReactFunction
    8 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
  • How to Generate Random Number in React JS?
    This article explores generating random numbers in React.js, accomplished through the utilization of the Math.random() method. Prerequisites:Introduction to ReactReact statesReact eventsJSX syntaxApproachTo generate Random numbers in React JS we will be using the Math.random and Math.floor methods a
    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