iway1 / react-ts-form

https://react-ts-form.com
MIT License
2.01k stars 33 forks source link

add schema-aware field hooks #95

Closed tyler-mitchell closed 1 year ago

tyler-mitchell commented 1 year ago

Introduces hooks which allow access to a field's schema data from within a custom form component via hooks.

Use cases:

This pull request adds capabilities referenced in #71

useFieldInfo

Returns schema-related information for any field.

Additionally, this hook includes label and placeholder which is currently gotten via the useDescription hook.

import { useFieldInfo } from "@ts-form/react";

const MyCustomField = () => {
  const { label, placeholder, isOptional, zodType } = useFieldInfo();
  return (
    <div>
      {label}
      <input placeholder={placeholder} required={!isOptional} />
    </div>
  );
};

useStringFieldInfo

Returns schema-related information for a ZodString field

import { useStringFieldInfo } from "@ts-form/react";

const MyStringCustomField = () => {

  const { label, placeholder, isOptional, minLength, maxLength, zodType } =
    useStringFieldInfo();

  return (
    <div>
      {label}
      <input
        placeholder={placeholder}
        required={!isOptional}
        minLength={minLength}
        maxLength={maxLength}
      />
    </div>
  );
};

useNumberFieldInfo

Returns schema-related information for a ZodNumber field

import { useNumberFieldInfo } from "@ts-form/react";

const MyNumberCustomField = () => {
  const { label, placeholder, isOptional, minValue, maxValue, isInt, zodType } =
    useNumberFieldInfo();
  return (
    <div>
      {label}
      <input
        placeholder={placeholder}
        required={!isOptional}
        min={minValue}
        max={maxValue}
        step={isInt ? undefined : 0.1}
      />
    </div>
  );
};
vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated
react-ts-form ✅ Ready (Inspect) Visit Preview 💬 Add your feedback Mar 24, 2023 at 4:46AM (UTC)
scamden commented 1 year ago

@iway1 we could really use this metadata as well! any chance you could review?

iway1 commented 1 year ago

@scamden yep will check it out in a bit

tyler-mitchell commented 1 year ago

@iway1

Glad to contribute 🔥