How to add color picker in React
In React, we can add a color picker using a library that simplifies color handling in applications. For this purpose, we will use the library react-color-palette that helps developers to easily incorporate color pickers into their React applications easily.
Installing dependencies
We'll need to install a few packages using npm, so make sure that your React application is built before we proceed.
You can see here how to create a React application.
Navigate to the root directory of your React project and install the dependencies using the following commands. We can name the folder as 'reactColor'.
cd reactColornpm i react-color-palette
Rendering color picker in React
Let's see how the react-color-palette helps to render canvas in your application.
import React from "react";
import { ColorPicker, useColor } from "react-color-palette";
import "react-color-palette/lib/css/styles.css";
export default function App() {
const [color, setColor] = useColor("hex", "#00FF00");
return (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
<h1>Color picker</h1>
<ColorPicker
width={600}
height={400}
color={color}
onChange={setColor}
hideHSV
dark
/>
</div>
);
}
Line 6: The
useColorhook is used to initialize thecolorstate, which holds the currently selected color. The initial color is set to#00FF00that is Green.Lines 11–18: The
ColorPickercomponent is placed, which is given awidthof 600 pixels and aheightof 400 pixels. It is configured to use thecolorstate and update it when the color selection changes using theonChangeprop and thesetColorfunction.
Below is a table presenting some of the props available for the ColorPicker component from the react-color-palette library:
ColorPicker props
Name | Type | Default | Description |
Width |
|
| The width of the color picker |
Height |
| width | The height of the color picker |
Color |
|
| The current |
The onChange |
|
| A function to update |
The onChangeComplete |
| undefined | A callback is called every time the user stops changing a color |
The hideHEX |
| false | Hide HEX input |
The hideRGB |
| false | Hide RGB input |
The hideHSV |
| false | Hide HSV input |
Alpha |
| false | Enable alpha channel |
Dark |
| false | Color theme |
Free Resources