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.
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
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 useColor
hook is used to initialize the color
state, which holds the currently selected color. The initial color is set to #00FF00
that is Green.
Lines 11–18: The ColorPicker
component is placed, which is given a width
of 600 pixels and a height
of 400 pixels. It is configured to use the color
state and update it when the color selection changes using the onChange
prop and the setColor
function.
Below is a table presenting some of the props available for the ColorPicker
component from the react-color-palette
library:
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 |