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.

Color picker in React
Color picker in React

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 reactColor
npm i react-color-palette
Installing color palette package in React

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>
  );
}
Rendering color picker in React application
  • 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 1118: 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:

ColorPicker props

Name

Type

Default

Description

Width

number

The width of the color picker

Height

number

width

The height of the color picker

Color

Color

The current Color

The onChange

Function

A function to update Color

The onChangeComplete

Function

undefined

A callback is called every time the user stops changing a color

The hideHEX

bool

false

Hide HEX input

The hideRGB

bool

false

Hide RGB input

The hideHSV

bool

false

Hide HSV input

Alpha

bool

false

Enable alpha channel

Dark

bool

false

Color theme

Copyright ©2024 Educative, Inc. All rights reserved