useRandomColor
React hook to generate random colors.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useRandomColor
sh
npx @novajslabs/cli add useRandomColor
sh
pnpm dlx @novajslabs/cli add useRandomColor
Or copy and paste the code into your project:
ts
import {useState} from "react";
export const useRandomColor = (initialColor?: string) => {
const [color, setColor] = useState(initialColor ?? "#000000");
const generateColor = () => {
const newColor =
"#" +
Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, "0");
setColor(newColor);
return newColor;
};
return {color, generateColor};
};
js
import {useState} from "react";
export const useRandomColor = (initialColor) => {
const [color, setColor] = useState(initialColor ?? "#000000");
const generateColor = () => {
const newColor =
"#" +
Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, "0");
setColor(newColor);
return newColor;
};
return {color, generateColor};
};
Requirements
React 16.8 or higher
Parameters
initialColor
Type: string
The initial value of the color.
Return values
color
Type: string
The currently generated color in hexadecimal format.
generateColor
Type: function
Generates and returns a random color in hexadecimal format.