DEV Community

Cover image for Simple REACT Projects || Random color project
TD!
TD!

Posted on

Simple REACT Projects || Random color project

It's Day #4 of #100daysofMiva. See Git repository for Random color project.

The provided React component, RandomColor, generates and displays random colors in either HEX or RGB format. Users can switch between these formats and generate new colors using buttons.

Image description

I did not encounter much trouble with the project because I already did most of the battle yesterday. So let's dive in:

Image description

getRandomNumber Function

function getRandomNumber(limit) {
  return Math.floor(Math.random() * limit);
Enter fullscreen mode Exit fullscreen mode

This function generates a random integer between '0' and 'limit - 1'.

generateRandomHexColor Function

function generateRandomHexColor() {
  const hexChars = "0123456789ABCDEF";
  let hexColor = "#";

  for (let i = 0; i < 6; i++) {
    hexColor += hexChars[getRandomNumber(16)];
  }

  return hexColor;
}
Enter fullscreen mode Exit fullscreen mode

This function generates a random HEX color by randomly selecting characters from the string '0123456789ABCDEF'.

generateRandomRgbColor Function

function generateRandomRgbColor() {
  const r = getRandomNumber(256);
  const g = getRandomNumber(256);
  const b = getRandomNumber(256);

  return `rgb(${r},${g},${b})`;
}
Enter fullscreen mode Exit fullscreen mode

This function generates a random RGB color by generating random values for red, green, and blue channels.

Rendering the Component

The component is rendered with three buttons: one to switch to HEX, one to switch to RGB, and one to generate a new color in the current format. The color type and value are displayed in a visually appealing manner.

return (
  <div style={containerStyles}>
    <button style={buttonStyles} onClick={() => setTypeOfColor("hex")}>
      Create HEX Color
    </button>
    <button style={buttonStyles} onClick={() => setTypeOfColor("rgb")}>
      Create RGB Color
    </button>
    <button style={buttonStyles} onClick={generateColor}>
      Generate Random Color
    </button>
    <div style={colorDisplayStyles}>
      <h3>{typeOfColor === "rgb" ? "RGB Color" : "HEX Color"}</h3>
      <h1>{color}</h1>
    </div>
  </div>
);

Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
mayowakalejaiye profile image
mayowa-kalejaiye

Super!!💪

Collapse
 
marvellye profile image
Ezekiel Marvellous

Amazing 🤲🏻

Collapse
 
damilola_oyeyipo_1348716f profile image
Damilola Oyeyipo

Colorful 😍

Collapse
 
abdul_web profile image
Abdulsamod

Nice work