Blog>
Snippets

Creating a Custom Input Hook with TanStack Form

Showcases how to create a custom input hook using TanStack Form for managing the state and validation of a text input field in a form, focusing on reusability and modularity.
import { useForm, Controller } from 'react-hook-form';
Import useForm and Controller from react-hook-form library to handle the form logic and control the custom input.
const useCustomInputHook = ({ name, rules, defaultValue = '' }) => {
  const { control, formState: { errors } } = useForm();
  const errorMessage = errors[name]?.message;

  const InputComponent = () => (
    <Controller
      name={name}
      control={control}
      rules={rules}
      defaultValue={defaultValue}
      render={({ field }) => (
        <input {...field} />
      )}
    />
  );

  return { InputComponent, errorMessage };
};
Defines a custom input hook using useForm and Controller. This hook accepts an object with name, rules for validation, and defaultValue. It returns an InputComponent for rendering and an errorMessage for displaying any validation errors.
const TextField = useCustomInputHook({
  name: 'username',
  rules: { required: 'Username is required' },
  defaultValue: 'JohnDoe'
});
Utilizes the custom input hook to create a text field. This example sets up a username field that is required with a default value of 'JohnDoe'.
const App = () => (
  <form>
    <TextField.InputComponent />
    {TextField.errorMessage && <p>{TextField.errorMessage}</p>}
    <button type='submit'>Submit</button>
  </form>
);
Demonstrates how to use the custom input (TextField) in a form component. It renders the input field and displays any error message under the field.