Skip to content
Related Articles

Related Articles

How to generate random colors by using React hooks ?

Improve Article
Save Article
Like Article
  • Last Updated : 29 Oct, 2021

We are going to make a react custom hook for generating random colors.

Pre-requisite:

Approach: Basically, if we are familiar with React , then we all have already used react custom hooks(like useState, useEffect , useContext etc.). We can also make our custom react hooks and can use it wherever we want. So there’s a small code for generating random colors. Here we will be making a random color generator custom hook (in our custom hook file), here we will make a function for changing color called (generateColor) , and we will be passing color and generate color as return. Then we will use this in our App.js by destructuring and will use that generate color as an onClick event function for a button through which we will change the color of our window.

Creating 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: Our folder structure should be like this.

Folder structure

Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :

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 4: Now go to src/App.js and paste the below code to use our random color generator custom hook.

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;

Now we are good to go with our react app .

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

npm start

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!