From bbb1312295c73c4cc6300cf0a6bde935c885d985 Mon Sep 17 00:00:00 2001 From: Ras Abdoellah Date: Fri, 21 Apr 2023 15:07:19 -0700 Subject: [PATCH 1/2] Fix hex input showing NaN when typing in hex value --- src/color-picker.js | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/color-picker.js b/src/color-picker.js index 64d2c29..2be52cd 100644 --- a/src/color-picker.js +++ b/src/color-picker.js @@ -11,11 +11,12 @@ import { hsv2rgb, } from '@swiftcarrot/color-fns'; import { rgba2hex } from './utils'; +import { useEffect, useState } from 'react'; const KEY_ENTER = 13; const ColorPicker = ({ color, onChange, disabled }) => { - const { r, g, b, a, h, s, v } = color; + const { r, g, b, a, h, s, v, hex } = color; function changeColor(color) { if (onChange) { @@ -44,9 +45,15 @@ const ColorPicker = ({ color, onChange, disabled }) => { } function changeHex(hex) { + + const hexRegx = /^#(?:[0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{8})$/i const { r, g, b } = hex2rgb(hex); const { h, s, v } = rgb2hsv(r, g, b); - changeColor({ ...color, r, g, b, h, s, v, hex }); + + if(hexRegx.test(hex)) { + changeColor({ ...color, r, g, b, h, s, v, hex }); + } + } function handleHexKeyUp(e) { @@ -68,6 +75,14 @@ const ColorPicker = ({ color, onChange, disabled }) => { const opacityGradient = `linear-gradient(to right, ${rgba0}, ${rgba100})`; const hueBackground = hsv2hex(h, 100, 100); + const [hexInput, setHexInput] = useState(hex) + + //reset hexInput if hex value is changed through another UI interaction + useEffect(() => { + setHexInput(hex) + },[hex]) + + return (
@@ -163,8 +178,11 @@ const ColorPicker = ({ color, onChange, disabled }) => { changeHex(e.target.value)} + value={hexInput} + onChange={(e) => setHexInput(e.target.value)} + onBlur={() => { + changeHex(hexInput) + }} onKeyUp={handleHexKeyUp} disabled={disabled} /> From e729c78ece30100432bcf29e44bc1dfcd8227b9a Mon Sep 17 00:00:00 2001 From: Ras Abdoellah Date: Fri, 21 Apr 2023 15:14:42 -0700 Subject: [PATCH 2/2] simplified handleHexKeyUp --- src/color-picker.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/color-picker.js b/src/color-picker.js index 2be52cd..44c8801 100644 --- a/src/color-picker.js +++ b/src/color-picker.js @@ -58,9 +58,8 @@ const ColorPicker = ({ color, onChange, disabled }) => { function handleHexKeyUp(e) { if (e.keyCode === KEY_ENTER) { - const hex = e.target.value.trim(); - const { r, g, b } = hex2rgb(hex); - changeColor({ ...color, r, g, b, a, hex }); + const hex = hexInput.trim(); + changeHex(hex) } }