How to design a HEX to RGB converter using ReactJS
Do you know how to create a reverse HEX to RGB converter ? If not, please read the instructions for designing this tool in React.js below.
This web application is developed using ReactJS , converting color codes from HEX to RGB and vice versa. It is a user-friendly color conversion tool that supports real-time preview, error correction and copying color values to clipboard.
Necessary conditions:
- React JS
- CSS
- React Hooks
- NPM and NPX
Steps to create a Hex to RGB converter using ReactJS
Create a react app using this command:
npx create-react-app hex-to-rgb-converter
After creating the project directory, e.g. hex-to-rgb-converter, use the following command to navigate to it:
cd hex-to-rgb-converter
Project structure
Package.json
"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" }
Method
- It uses state variables to store HEX and RGB values, useRef for input field references.
- The valid and invalid functions handle input validation and error reporting.
- toRgb converts HEX to RGB and sets the document background color.
- toHex converts RGB to HEX and vice versa.
- The functions 'copyRgbToClipboard' and 'copyHexToClipboard' copy values to the clipboard.
- This component provides input fields, button copy, and a color picker.
- Errors are displayed as red text and the background color of the document is updated.
For example
JavaScript
import React, { useState, useRef } from 'react'; import './App.css'; function App() { const [hexValue, setHexValue] = useState(''); const [rgbValue, setRgbValue] = useState(''); const hexInputRef = useRef(null); const rgbInputRef = useRef(null); const [error, setError] = useState(''); function valid(element) { element.style.color = '#202040'; setError(''); } function invalid(element, otherElement, errorMessage) { element.style.color = '#f04624'; otherElement(''); setError(errorMessage); } function toRgb(hexCode) { const rgbArr = []; if (/^#?[A-Fa-f0-9]{6}$/.test(hexCode)) { valid(hexInputRef.current); hexCode = hexCode.split('#')[1] || hexCode; for (let i = 0; i < hexCode.length; i += 2) { rgbArr.push(parseInt(hexCode[i] + hexCode[i + 1], 16)); } setRgbValue(`rgb(${rgbArr.join(', ')})`); document.body.style.backgroundColor = `rgb(${rgbArr.join(', ')})`; } else { invalid(hexInputRef.current, setRgbValue, 'Invalid HEX value'); } } function toHex(rgbCode) { const rgbRegex1 = /^rgb([0-9]{1,3},[0-9]{1,3},[0-9]{1,3})$/; const rgbRegex2 = /^[0-9]{1,3},[0-9]{1,3},[0-9]{1,3}$/; let hex = '#'; if (rgbRegex1.test(rgbCode) || rgbRegex2.test(rgbCode)) { rgbCode = rgbCode.replace(/[rgb()]+/g, '') || rgbCode; rgbCode = rgbCode.split(','); const condition = rgbCode.every((value) => parseInt(value) <= 255); if (condition) { valid(rgbInputRef.current); rgbCode.forEach((value) => { value = parseInt(value).toString(16); hex += value.length === 1 ? '0' + value : value; }); setHexValue(hex); document.body.style.backgroundColor = hex; } else { invalid(rgbInputRef.current, setHexValue, 'Invalid RGB value'); } } else { invalid(rgbInputRef.current, setHexValue, 'Invalid RGB value'); } } function copyRgbToClipboard() { const rgbInput = document.getElementById('rgb'); rgbInput.select(); document.execCommand('copy'); } function copyHexToClipboard() { const hexInput = document.getElementById('hex'); hexInput.select(); document.execCommand('copy'); } return (
GeeksForGeeks
HEX To RGB Converter
{ setRgbValue(e.target.value); toHex(e.target.value); }} ref={rgbInputRef} placeholder="Enter RGB Value" /> { setHexValue(e.target.value); toRgb(e.target.value); }} ref={hexInputRef} placeholder="Enter Hex Value" /> {error &&
{error}
} { const selectedColor = e.target.value; setHexValue(selectedColor); toRgb(selectedColor); }} /> ); } export default App;
CSS
.container { background-color: #f5f5f5; padding: 20px; border-radius: 10px; max-width: 450px; margin: 0 auto; box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.2); } .wrapper { display: flex; flex-direction: column; margin: 15px 0; } label { font-weight: 600; margin-bottom: 8px; } h1 { text-align: center; color: #308d46; font-weight: bold; margin-bottom: 10px; padding: 10px; border-radius: 10px; } h2 { text-align: center; color: #0984e3; font-weight: bold; font-family: 'Courier New', Courier, monospace; border-bottom: 5px solid #0984e3; margin-bottom: 10px; padding: 10px; border-radius: 10px; } input { width: 93%; padding: 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 15px; outline: none; box-shadow: 0 2px 14px rgba(0, 0, 0, 0.1); transition: border-color 0.2s, box-shadow 0.2s; } input:focus { border-color: #202040; box-shadow: 0 4px 18px rgba(32, 32, 64, 0.2); } button { background-color: #0984e3; color: white; border: none; padding: 15px; margin-top: 15px; border-radius: 10px; cursor: pointer; transition: background-color 0.2s, transform 0.2s; } button:hover { background-color: #404080; transform: scale(1.05); } .color-picker { display: flex; flex-direction: column; margin: 15px 0; } .color-picker input { margin-top: 8px; height: 70px; width: 100%; cursor: pointer; } p { color: red; margin: 8px 0; } body { background-color: #f0f0f0; font-family: 'Arial', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; } @media (max-width: 768px) { .container { max-width: 100%; } input, button { padding: 10px; font-size: 14px; } }
Steps to run the application
Enter the following command into terminal:
npm start
Enter the following URL in the browser:
http://localhost:3000/
Result:
Hope this article is useful to you!
You should read it
- Convert PDF to Word, convert PDF files for free
- How to convert PNG images to JPG does not degrade quality
- how to convert a JPG file to PDF with just one operation
- How to convert AI files to PNG, JPG without software
- How to convert JPG images to PNG
- Simple way to convert Excel files to PDF
- How to convert WAV format to MP3 using LAME with Audacity
- Guide to convert MP4 to 3GP
May be interested
- Link to download PDF To Word Converter Free 3.5free pdf to word converter is a free cloud-based application that allows you to convert pdf files into microsoft word files.
- 6 tools to convert audio to video onlineif there's an audio file that you want to tweak a bit, you might want to consider converting it to a video first. for example, if you are uploading something to youtube or creating a presentation, additional images can be of great benefit.
- 5 best applications to convert audio and video files on Linuxlinux users are spoiled for choice when it comes to open source audio and video converters. here are the best media converters available today for linux, including a range of different file formats.
- 6 best free online Markdown editors and convertersif you need a tool that allows you to write in markdown or give you the ability to convert a document into markdown, here is a list of the best markdown editors to perform both of these tasks.
- Download offers, Unit Converter (Pega Pro), application converted more than 12800 units, are freeunit converter (pega pro) is a conversion application for android devices, supporting users to perform unit conversions with about 12,800 different units of measurement.
- How to install PDF to Word Converter on your computer quickly and simplypdf to word converter helps you convert pdf files to word quickly, supporting many formats such as doc, rtf. this software is especially useful for office workers, teachers, and students who need to edit pdf content easily.
- Google launched Squoosh, an online photo conversion applicationthe chrome developer conference of google is taking place and one of the newly unveiled yesterday is squoosh, the online application to showcase browser capabilities.
- Offering free license for HD Video Converter Factory Pro, video conversion software costs USD 49.95hd video converter factory pro is a professional video conversion software with many powerful features, supporting users to convert hd videos to many other popular formats and mobile devices at a fast speed.
- How to convert FLAC to MP3 formatbecause flac files are not compressed, they are often very large and consume a lot of storage space. the good news is that you can easily convert your flac files to a more user-friendly mp3 format.
- How to use File Converter to batch convert files from the right-click menufile converter is a software to convert files right from the right-click menu without you having to access the application to convert file formats.