Open In App

RGB Color Slider Using React js

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a RGB color slider Using ReactJS. The RGB Color Slider web application offers an interactive way for users to choose and preview colors via red, green, and blue sliders. Among its features, it sports a real-time visualization of the selected color, as well as allows users to copy RGB and HEX color codes, generate random colors, and choose from preset colors.

Preview of final output: Let us have a look at how the final output will look like.RGB-Color-Slider-Using-React-js

Prerequisite

Approach:

  • Constructor and Initial State: Initialize the component’s state with color values, results, and presets.
  • generateColor(): Calculate RGB color, update state, and set background color.
  • updateHexColor(): Convert RGB to HEX and update the state.
  • rgbToHex(): Utility to convert RGB to HEX.
  • copyColorCode(): Copy RGB or HEX to clipboard and manage “Copied!” status.
  • handleSliderChange(): Handle slider adjustments and trigger color generation.
  • handlePresetClick(): Handle preset color clicks and update the color.
  • generateRandomColor(): Generate a random color and update the state.
  • Rendering: Return JSX for the user interface, including sliders, presets, copy buttons, and a “Random Color” button.

Steps to Create the project:

Step 1: Create a react application by using this command

npx create-react-app ColorSliderApp

Step 2: After creating your project folder, i.e. ColorSliderApp, use the following command to navigate to it:

cd ColorSliderApp

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
 }

Example: Below is the implementation of the above approach

Javascript




import React, { Component } from 'react';
import './App.css';
 
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            redValue: 0,
            greenValue: 0,
            blueValue: 0,
            resultColor: 'rgb(0,0,0)',
            hexColor: '#000000',
            copyButtonClicked: false,
            presets: [
                {
                    redValue: 255, greenValue: 0,
                    blueValue: 0, label: 'Red'
                },
                {
                    redValue: 0, greenValue: 255,
                    blueValue: 0, label: 'Green'
                },
                {
                    redValue: 0, greenValue: 0,
                    blueValue: 255, label: 'Blue'
                },
                {
                    redValue: 255, greenValue: 255,
                    blueValue: 0, label: 'Yellow'
                },
                {
                    redValue: 255, greenValue: 0,
                    blueValue: 255, label: 'Magenta'
                },
                {
                    redValue: 0, greenValue: 255,
                    blueValue: 255, label: 'Cyan'
                },
            ],
        };
    }
 
    generateColor = () => {
        const { redValue, greenValue,
            blueValue } = this.state;
        const finalColor =
            `rgb(${redValue}, ${greenValue},
                ${blueValue})`;
        this.setState({ resultColor: finalColor });
        this.updateHexColor(finalColor);
        document.body.style.backgroundColor = finalColor;
    };
 
    updateHexColor = (rgbColor) => {
        const hexColor =
            this.rgbToHex(rgbColor);
        this.setState({ hexColor });
    };
 
    rgbToHex = (rgb) => {
        const rgbValues = rgb.match(/\d+/g);
        const hexColor = `#${Number(rgbValues[0])
            .toString(16)
            .padStart(2, '0')}${Number(rgbValues[1])
                .toString(16)
                .padStart(2, '0')}${Number(rgbValues[2])
                    .toString(16).padStart(2, '0')}`;
        return hexColor;
    };
 
    copyColorCode = (codeType) => {
        const resultInput =
            document.getElementById(`${codeType}-input`);
        resultInput.select();
        document.execCommand('copy');
        this.setState({ copyButtonClicked: codeType });
 
        setTimeout(() => {
            this.setState({ copyButtonClicked: false });
        }, 1000);
    };
 
    handleSliderChange = (event, color) => {
        this.setState(
            { [`${color}Value`]: event.target.value },
            this.generateColor
        );
    };
 
    handlePresetClick = (preset) => {
        this.setState(
            {
                redValue: preset.redValue,
                greenValue: preset.greenValue,
                blueValue: preset.blueValue,
            },
            this.generateColor
        );
    };
 
    generateRandomColor = () => {
        const randomColor = {
            redValue:
                Math.floor(Math.random() * 256),
            greenValue:
                Math.floor(Math.random() * 256),
            blueValue:
                Math.floor(Math.random() * 256),
        };
        this.setState(randomColor, this.generateColor);
    };
 
    render() {
        const {
            redValue,
            greenValue,
            blueValue,
            resultColor,
            hexColor,
            copyButtonClicked,
            presets,
        } = this.state;
 
        return (
            <div className="container">
                <div className="wrapper">
                    <label htmlFor="red">R</label>
                    <input
                        type="range"
                        min="0"
                        max="255"
                        value={redValue}
                        id="red"
                        onChange=
                        {(e) =>
                            this.handleSliderChange(e, 'red')}
                    />
                </div>
                <div className="wrapper">
                    <label htmlFor="green">G</label>
                    <input
                        type="range"
                        min="0"
                        max="255"
                        value={greenValue}
                        id="green"
                        onChange={
                            (e) =>
                                this.handleSliderChange(e, 'green')}
                    />
                </div>
                <div className="wrapper">
                    <label htmlFor="blue">B</label>
                    <input
                        type="range"
                        min="0"
                        max="255"
                        value={blueValue}
                        id="blue"
                        onChange={
                            (e) =>
                                this.handleSliderChange(e, 'blue')}
                    />
                </div>
                <div className="presets">
                    {presets.map((preset, index) => (
                        <button key={index}
                            onClick={
                                () =>
                                    this.handlePresetClick(preset)}>
                            {preset.label}
                        </button>
                    ))}
                </div>
                <div className="result">
                    <input type="text"
                        id="result-input"
                        value={resultColor} readOnly />
                    <button onClick={
                        () =>
                            this.copyColorCode('result')}>
                        {copyButtonClicked ===
                            'result' ? 'Copied!' :
                            'Copy RGB Color Code'}
                    </button>
                    <input type="text"
                        id="hex-input"
                        value={hexColor} readOnly />
                    <button onClick={
                        () =>
                            this.copyColorCode('hex')}>
                        {copyButtonClicked ===
                            'hex' ?
                            'Copied!' :
                            'Copy Hex Color Code'}
                    </button>
                </div>
                <div className="random-color">
                    <button
                        onClick=
                            {this.generateRandomColor}>
                        Random Color
                    </button>
                </div>
            </div>
        );
    }
}
 
export default App;


CSS




body {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f2f2f2;
}
 
.container {
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 2em 3em rgba(0, 0, 0, 0.2);
    margin: 10px;
    padding: 30px;
    max-width: 400px;
}
 
.wrapper {
    display: flex;
    align-items: center;
    gap: 1em;
    margin-bottom: 5px;
}
 
label {
    font-size: 1.8em;
}
 
input[type='range'] {
    width: 100%;
}
 
.result {
    width: 100%;
    display: grid;
    grid-template-columns: 7fr 5fr;
    gap: 1em;
}
 
input[type='text'],
button {
    font-size: 14px;
    border-radius: 0.5em;
    border: none;
    outline: none;
}
 
input[type='text'] {
    background-color: #ebeaea;
    padding: 10px;
    font-weight: 400;
}
 
input[type='text']::selection {
    background-color: transparent;
}
 
button {
    background-color: #0075ff;
    color: #ffffff;
    font-weight: 600;
    cursor: pointer;
    padding: 13px;
    margin: 10px;
}


Steps to run the application

Step 1: Type the following command in the terminal:

npm start

Step 2: Type the following URL in the browser:

 http://localhost:3000/

Output:

RGB-Color-Slider-Using-React-js



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads