TanStackT
TanStack2y ago
7 replies
living-lavender

Extracting the input element to make it reusable!

i this demo example everything works fine! But I need a way to extract out the input element into a separate component so that i don't need to write the input elelemnt again and again! But the problem becomes whever i tried to make a Field APi with general types the children prop of the form dont want to accept it! And normally i dont like using any it show a red mark (which is not that of a big deal) but something of personal preferrence!
import { useForm } from "@tanstack/react-form";
import ActionButton from "../../Common/Button/Button";

export default function LoginForm() {
  const form = useForm({
    defaultValues: {
      fullName: "Obaba",
      fine: true,
    },
    onSubmit: async ({ value }) => {
      // Do something with form data
      console.log(value);
    },
  });

  return (
    <div>
      <form.Provider>
        <form
          className="text-black"
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            void form.handleSubmit();
          }}
        >
          <div>
            <form.Field name="fullName" children={(field) => <input name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />} />
            <form.Field name="fine" children={(field) => <input type="checkbox" name={field.name} checked={field.state.value} onChange={(e) => field.handleChange(e.target.checked)} />} />
          </div>
          <ActionButton text="Login" type="submit" />
        </form>
      </form.Provider>
    </div>
  );
}
Was this page helpful?