In web development, colors play a vital role in creating visually appealing and engaging user interfaces. As a React developer, you may often find yourself needing to generate random colors dynamically. In this article, we will explore how to achieve this using React hooks, a powerful feature introduced in ReactJs.
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.
Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :
Javascript
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.
Javascript
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: