Skip to content

Commit

Permalink
Improve HexColorInput typing
Browse files Browse the repository at this point in the history
  • Loading branch information
omgovich authored and Vlad Shilov committed Sep 14, 2020
1 parent ebe0ddb commit a641007
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/components/HexColorInput.tsx
Expand Up @@ -6,13 +6,18 @@ import { validHex } from "../utils/validate";
// Escapes all non-hexadecimal characters including "#"
const escape = (hex: string) => hex.replace(/([^0-9A-F]+)/gi, "");

interface Props extends HTMLInputElement {
interface ComponentProps {
color: string;
onChange: (newColor: string) => void;
}

const HexColorInputBase = (props: Partial<Props>) => {
const { color = "", onChange } = props;
type InputProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
"onChange" | "onBlur" | "maxLength" | "value"
>;

export const HexColorInput = (props: Partial<InputProps & ComponentProps>): JSX.Element => {
const { color = "", onChange, ...rest } = props;
const [value, setValue] = useState(() => escape(color));
const onChangeCallback = useEventCallback<string>(onChange);

Expand All @@ -39,17 +44,14 @@ const HexColorInputBase = (props: Partial<Props>) => {
setValue(escape(color));
}, [color]);

// Spread operator replacement to get rid of the polyfill (saves 150 bytes gzipped)
const inputProps = Object.assign({}, props, {
color: null, // do not add `color` attr to `input`-tag
value,
maxLength: 6,
spellCheck: "false", // the element should not be checked for spelling errors
onChange: handleChange,
onBlur: handleBlur,
});

return React.createElement("input", inputProps);
return (
<input
{...rest}
value={value}
maxLength={6}
spellCheck="false" // the element should not be checked for spelling errors
onChange={handleChange}
onBlur={handleBlur}
/>
);
};

export const HexColorInput = React.memo<Partial<Props>>(HexColorInputBase);

0 comments on commit a641007

Please sign in to comment.