Open In App

How to generate random colors by using React hooks ?

Improve
Improve
Like Article
Like
Save
Share
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:

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.



Last Updated : 09 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads