Color picker in React using react-color
Today we’ll show you how to implement color picker in React using react-color. With the help of this npm package, we can implement 13 different types of the pickers such as Chrome, Photoshop, Sketch and many more.
In this article, we will take an example to pick color from color picker and display rgba or hex color code. Mostly we have to use a color picker in e-commerce or shopping sites.
Steps to implement color picker
1. Setup a react project
In the first step, we will set up a basic react application using create-react-app
. Refer to this link for more information.
Run the following code to create a react application.
1 | npx create-react-app color-picker-react |
2. Install dependency
As we mentioned, we will use the react-color npm package. So let’s install the npm package in react project by running the following command.
1 | npm i react-color |
3. Implement color picker
Now it’s time to implement color picker in App.js
file. Here we will display the SketchPicker
component from the react-color and we will show the selected HEX
color. You can also store the RGB
color.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import React, { useState } from 'react'; import { SketchPicker } from 'react-color'; function App() { const [colorHexCode, setColorHexCode] = useState('#000000'); return ( <div className="App"> <h3>React color picker - <a href="https://www.cluemediator.com">Clue Mediator</a></h3> <SketchPicker color={colorHexCode} onChange={e => setColorHexCode(e.hex)} /> <br /> <b>Selected Hex Color: </b>{colorHexCode} </div> ); } export default App; |
4. Output
Run the project and checkout the output.
That’s it for today.
Thank you for reading. Happy Coding..!!