Skip to content

Commit

Permalink
fix: Display ValidatedInput errors below input field (#430)
Browse files Browse the repository at this point in the history
  • Loading branch information
maciaszczykm authored Mar 7, 2023
1 parent 7682379 commit a3e8f05
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 17 deletions.
19 changes: 4 additions & 15 deletions src/components/ValidatedInput.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import {
PropsWithChildren,
ReactElement,
ReactNode,
Ref,
createElement,
forwardRef,
useCallback,
useState,
} from 'react'
import PropTypes from 'prop-types'
import { Input, InputProps, Span } from 'honorable'
import { Input, InputProps } from 'honorable'

import FormField from './FormField'

Expand All @@ -19,7 +17,6 @@ export type CaptionProps = {caption: string, color: string}
export type ValidatedInputProps = InputProps & PropsWithChildren<{
label?: ReactNode
hint?: ReactNode
caption?: (props: CaptionProps) => ReactElement
validation?: (val: string) => ValidationResponse
}>

Expand All @@ -30,29 +27,21 @@ const propTypes = {
validation: PropTypes.func,
}

function defaultCaption({ caption, color }: CaptionProps) : ReactElement {
return (
<Span color={color}>{caption}</Span>
)
}

function ValidatedInputRef({
label, hint, validation, onChange, width, caption, ...input
label, hint, validation, onChange, width, ...input
} : ValidatedInputProps, ref: Ref<any>) {
const [error, setError] = useState(null)
const wrappedOnChange = useCallback((e: any) => {
if (onChange) onChange(e)
setError((validation && e.target?.value) ? validation(e.target.value) : undefined)
}, [onChange, validation])

const captionComp = caption || defaultCaption

return (
<FormField
ref={ref}
label={label}
hint={hint}
caption={error ? createElement(captionComp, { caption: error.message, color: error.error ? 'text-danger' : 'text-success' }) : null}
hint={error?.error ? error.message : hint}
error={!!error?.error}
width={width}
>
<Input
Expand Down
5 changes: 3 additions & 2 deletions src/stories/ValidatedInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ function Template() {
value={value}
onChange={(e: any) => setValue(e.target.value)}
width="500px"
label="input needs to be looong"
validation={(v: string) : ValidationResponse => (v.length < 4 ? { error: true, message: 'too short' } : { error: false, message: 'long enough!' })}
label="Name"
hint="Name needs to be at least 5 characters long."
validation={(v: string) : ValidationResponse => (v.length < 5 ? { error: true, message: 'Provided name is too short. Name needs to be at least 5 characters long.' } : null)}
/>
)
}
Expand Down

0 comments on commit a3e8f05

Please sign in to comment.