Skip to content

Commit

Permalink
fix: Add error helper to NumField component
Browse files Browse the repository at this point in the history
  • Loading branch information
d4n1b committed Oct 8, 2024
1 parent 7307432 commit 318f39b
Showing 1 changed file with 35 additions and 22 deletions.
57 changes: 35 additions & 22 deletions src/NumField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,22 @@
* under the License.
*/

import * as React from "react";
import { Ref } from "react";
import { TextInput, TextInputProps } from "@patternfly/react-core/dist/js/components/TextInput";
import { connectField } from "uniforms";
import wrapField, { WrapFieldProps } from "./wrapField";
import * as React from 'react';
import { Ref } from 'react';
import { TextInput, TextInputProps } from '@patternfly/react-core/dist/js/components/TextInput';
import { connectField } from 'uniforms';
import wrapField, { WrapFieldProps } from './wrapField';
import { FormHelperText, HelperText, HelperTextItem } from '@patternfly/react-core';
import { ExclamationCircleIcon } from '@patternfly/react-icons';

export type NumFieldProps = {
id: string;
decimal?: boolean;
inputRef?: Ref<HTMLInputElement>;
onChange: (value?: number) => void;
disabled?: boolean;
errorMessage?: string;
helperText?: string;
value?: number;
error?: boolean;
} & Omit<TextInputProps, 'isDisabled'> &
Expand All @@ -37,28 +41,37 @@ export type NumFieldProps = {
function NumField(props: NumFieldProps) {
const onChange = (value: string, event: React.FormEvent<HTMLInputElement>) => {
const parse = props.decimal ? parseFloat : parseInt;
const v = parse((event.target as any)?.value ?? "");
const v = parse((event.target as any)?.value ?? '');
props.onChange(isNaN(v) ? undefined : v);
};

return wrapField(
props,
<TextInput
aria-label={"uniforms num field"}
data-testid={"num-field"}
name={props.name}
isDisabled={props.disabled}
id={props.id}
max={props.max}
min={props.min}
onChange={(event, value: string) => onChange(value, event)}
placeholder={props.placeholder}
ref={props.inputRef}
step={props.step ?? (props.decimal ? 0.01 : 1)}
type="number"
value={`${props.value ?? ""}`}
validated={props.error ? "error" : "default"}
/>
<>
<TextInput
aria-label="uniforms num field"
data-testid="num-field"
name={props.name}
isDisabled={props.disabled}
id={props.id}
max={props.max}
min={props.min}
onChange={(event, value: string) => onChange(value, event)}
placeholder={props.placeholder}
ref={props.inputRef}
step={props.step ?? (props.decimal ? 0.01 : 1)}
type="number"
value={props.value ?? ''}
validated={props.error ? 'error' : 'default'}
/>
<FormHelperText>
<HelperText>
<HelperTextItem icon={props.error && <ExclamationCircleIcon />} variant={props.error ? 'error' : 'default'}>
{!props.error ? props.helperText : props.errorMessage}
</HelperTextItem>
</HelperText>
</FormHelperText>
</>,
);
}

Expand Down

0 comments on commit 318f39b

Please sign in to comment.