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
- Generate a random color using a color library like chroma-js. 
- Create a state variable to store the palette size. 
- Create a state variable to store the generated colors. 
- Define a function to generate a new color palette based on the palette size. 
- Define a function to copy the color codes to the clipboard. 
- Render a preview of the colors with a copy button. 
Classes
ColorPaletteGenerator: A component that generates the color palette and renders the preview.
Code
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. 
Last updated