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 (
<div className="container">
<h1>GeeksForGeeks</h1>
<h2>HEX To RGB Converter</h2>
<div className="wrapper">
<label htmlFor="rgb">RGB</label>
<input
type="text"
id="rgb"
value={rgbValue}
onChange={(e) => {
setRgbValue(e.target.value);
toHex(e.target.value);
}}
ref={rgbInputRef}
placeholder="Enter RGB Value"
/>
<button onClick={copyRgbToClipboard}>Copy RGB</button>
</div>
<div className="wrapper">
<label htmlFor="hex">HEX</label>
<input
type="text"
id="hex"
value={hexValue}
onChange={(e) => {
setHexValue(e.target.value);
toRgb(e.target.value);
}}
ref={hexInputRef}
placeholder="Enter Hex Value"
/>
<button onClick={copyHexToClipboard}>Copy HEX</button>
</div>
{error && <p style={{ color: 'red' }}>{error}</p>}
<div className="color-picker">
<label htmlFor="color-picker">Color Picker:</label>
<input
type="color"
id="color-picker"
onChange={(e) => {
const selectedColor = e.target.value;
setHexValue(selectedColor);
toRgb(selectedColor);
}}
/>
</div>
</div>
);
}
export default App;