upon clicking the div the background color of div should changes as per the selected type of color either rgb or hex color mode but the problem is when type of color is hex ,things go perfectly fine, chnages the backgroud color randomly on clicking the div but on clicking rgb button rgb color value changes but background color dont change.
import { useState, useEffect } from 'react';
export default function RandomColor() {
const [typeOfColor, setTypeOfColor] = useState('rgb')
const [color, setColor] = useState('#000000')
function randomColorUtility(length) {
return Math.floor(Math.random() * length);
}
function handleCreateRandomHexColor() {
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
let hexColor = "#";
for (let i = 0; i < 6; i++) {
hexColor += hex[(randomColorUtility(hex.length))]
}
setColor(hexColor);
}
function handleCreateRandomRGBColor() {
let r = randomColorUtility(256);
let g = randomColorUtility(256);
let b = randomColorUtility(256);
setColor(`(${r},${g}, ${b})`);
}
useEffect(() => {
if (typeOfColor === "rgb") handleCreateRandomRGBColor();
else handleCreateRandomHexColor();
}, [typeOfColor]);
return (
<div onClick={
typeOfColor === "hex"
? () => handleCreateRandomHexColor()
: () => handleCreateRandomRGBColor()
}style={{
width: "100w",
height: "100vh",
background: {color},
}}>
<button onClick={() => setTypeOfColor("hex")}>Create HEX Color</button>
<button onClick={() => setTypeOfColor("rgb")}>Create RGB Color</button>
{/* <button onClick={handleCreateRandomColor}> Generate Random Color </button> */}
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "#fff",
fontSize: "60px",
marginTop: "50px",
flexDirection :'column',
gap :'20px'
}}>
<h3>{typeOfColor === "rgb" ? "RGB Color" : "Hex Color"} </h3>
<h1> {`${color}`}</h1>
</div>
</div>
);
}