Skip to content

Instantly share code, notes, and snippets.

@Sti2nd
Created December 17, 2021 19:55
Show Gist options
  • Save Sti2nd/00c8164c3af1e649a2b70690a39d0da2 to your computer and use it in GitHub Desktop.
Save Sti2nd/00c8164c3af1e649a2b70690a39d0da2 to your computer and use it in GitHub Desktop.
Example of FormField component
import { HTMLInputTypeAttribute, HTMLAttributes } from "react";
import { Form } from "react-bootstrap";
import { useFormContext } from "react-hook-form";
import { v4 as uuid } from "uuid";
interface IFormField {
/**
* The name attribute on the input field. Will be registered with
* react-hook-form.
*/
name: string;
labelText?: string;
placeholder?: string;
isValid?: boolean;
feedback?: string;
/**
* By default "text"
*/
type?: HTMLInputTypeAttribute;
autoFocus?: boolean;
defaultValue?: HTMLAttributes<HTMLInputElement>["defaultValue"];
}
/**
* A wrapper around the react-bootstrap Form.Group component. Has
* Label, Control and Feedback.
*/
export default function FormField({
labelText,
placeholder,
name,
isValid = true,
feedback,
type = "text",
autoFocus = false,
defaultValue,
}: IFormField) {
const htmlId = uuid();
const { register } = useFormContext();
const convertToIntOrUndefined = (value: string) => {
return value === "" ? undefined : parseInt(value, 10);
};
const converToStringOrUndefined = (value: string) => {
return value === "" ? undefined : value;
};
const transformValue = (v: string) => {
if (type === "text") {
return converToStringOrUndefined(v);
} else if (type === "number") {
return convertToIntOrUndefined(v);
}
return v;
};
return (
<Form.Group controlId={htmlId}>
<Form.Label>{labelText}</Form.Label>
<Form.Control
autoFocus={autoFocus}
type={type}
placeholder={placeholder}
{...register(name, {
setValueAs: (v) => transformValue(v),
})}
isValid={isValid}
isInvalid={!isValid}
defaultValue={defaultValue}
/>
<Form.Control.Feedback type="invalid">{feedback}</Form.Control.Feedback>
</Form.Group>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment