Cách thiết kế công cụ chuyển đổi HEX sang RGB bằng ReactJS

Bạn đã biết tạo công cụ chuyển đổi HEX sang RGB ngược lại chưa? Nếu chưa, mời bạn đọc hướng dẫn thiết kế công cụ này trong React.js dưới đây.

Ứng dụng web này được phát triển bằng cách dùng ReactJS, chuyển đổi code màu sắc từ HEX sang RGB và ngược lại. Nó là một công cụ chuyển đổi màu thân thiện người dùng có hỗ trợ xem trước tại thời gian thực, sửa lỗi và sao chép các giá trị màu vào clipboard.

Công cụ chuyển đổi HEX sang RGB

Điều kiện cần có:

  • React JS
  • CSS
  • React Hooks
  • NPM và NPX

Các bước tạo công cụ chuyển đổi Hex sang RGB bằng ReactJS

Tạo ứng dụng react bằng cách dùng lệnh này:

npx create-react-app hex-to-rgb-converter

Sau khi tạo thư mục dự án, ví dụ: hex-to-rgb-converter, dùng lệnh sau để điều hướng tới nó:

cd hex-to-rgb-converter

Cấu trúc dự án

Cấu trúc thư mục

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"
  }

Phương pháp

  • Nó dùng biến trạng thái để lưu trữ các giá trị HEX và RGB, useRef cho các tham chiếu trường đầu vào.
  • Hàm valid và invalid xử lý xác thực đầu vào và thông báo lỗi.
  • toRgb chuyển đổi HEX sang RGB và đặt màu nền tài liệu.
  • toHex chuyển đổi RGB sang HEX và ngược lại.
  • Hàm ‘copyRgbToClipboard’ và ‘copyHexToClipboard’ sao chép các giá trị vào clipboard.
  • Thành phần này cung cấp các trường nhập, sao chép nút bấm và một công cụ chọn màu.
  • Các lỗi được hiện dưới dạng text màu đỏ và cập nhật màu nền cho tài liệu.

Ví dụ

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 (
		<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;

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;
	}
}

Các bước chạy ứng dụng

Nhập lệnh sau vào terminal:

npm start

Nhập URL sau trong trình duyệt:

http://localhost:3000/

Kết quả:

Công cụ đổi màu HEX sang RGB

Hi vọng bài viết hữu ích với các bạn!

Thứ Năm, 02/11/2023 16:49
31 👨 106
0 Bình luận
Sắp xếp theo