> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/react-coding-puzzles/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/react-coding-puzzles/16-color-palette-generator.md).

# 16 - Color Palette Generator

### **Description**

Create a React application that generates a color palette with the following features:

* Start with a random color
* Adjust the palette size
* Preview the colors
* Copy color codes

### **Algorithm**

1. Generate a random color using a color library like chroma-js.
2. Create a state variable to store the palette size.
3. Create a state variable to store the generated colors.
4. Define a function to generate a new color palette based on the palette size.
5. Define a function to copy the color codes to the clipboard.
6. Render a preview of the colors with a copy button.

### **Classes**

`ColorPaletteGenerator`: A component that generates the color palette and renders the preview.

### **Code**

```javascript
import React, { useState } from 'react';
import chroma from 'chroma-js';

function ColorPaletteGenerator() {
  const [paletteSize, setPaletteSize] = useState(5);
  const [colors, setColors] = useState([]);

  const generatePalette = () => {
    const colors = [];
    for (let i = 0; i < paletteSize; i++) {
      colors.push(chroma.random().hex());
    }
    setColors(colors);
  };

  const copyColors = () => {
    const colorCodes = colors.join(', ');
    navigator.clipboard.writeText(colorCodes);
  };

  return (
    <div>
      <input
        type="number"
        value={paletteSize}
        onChange={(event) => setPaletteSize(event.target.value)}
      />
      <button onClick={generatePalette}>Generate Palette</button>
      <div>
        {colors.map((color) => (
          <div
            style={{ backgroundColor: color, width: 50, height: 50 }}
          />
        ))}
      </div>
      <button onClick={copyColors}>Copy Color Codes</button>
    </div>
  );
}

export default ColorPaletteGenerator;

```

### **Explanation**

The `ColorPaletteGenerator` component generates a color palette with a random color using chroma-js. The component uses the `useState` hook to store the palette size and generated colors. The `generatePalette` function generates a new color palette based on the palette size. The `copyColors` function copies the color codes to the clipboard. The component renders a preview of the colors with a copy button.

### Possible Future Enhancements:

* Add more features to the color palette generator (e.g., color harmony, contrast).
* Use a more advanced color library (e.g., color-thief).
* Display the color codes in a more user-friendly format (e.g., hex, rgb).
* Style the component with CSS.
