Blog>
Snippets

Integrating a Third-Party DatePicker with TanStack Form

Outline how to integrate a third-party date picker component into a form built with TanStack Form in a React Native application.
import { useForm, useField } from '@tanstack/react-form';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
First, import the useForm and useField hooks from TanStack Form, and also import the DatePicker component and its CSS from 'react-datepicker'.
const DatePickerField = ({ field }) => {
  const { getInputProps } = useField(field);
  const [fieldState, fieldHelpers] = getInputProps();
  return (
    <DatePicker
      selected={fieldState.value || null}
      onChange={date => fieldHelpers.setValue(date)}
    />
  );
};
Create a custom DatePickerField component that utilizes the useField hook to integrate with TanStack Form. The field's current value and a function to update it are obtained from getInputProps. These are then used to manage the DatePicker's selected value and handle changes.
function MyForm() {
  const { Form } = useForm({
    initialValues: { birthDate: '' },
    onSubmit: async (values) => {
      console.log(values);
    },
  });

  return (
    <Form>
      <div>
        <label htmlFor="birthDate">Birth Date</label>
        <DatePickerField field="birthDate" />
      </div>
      <button type="submit">Submit</button>
    </Form>
  );
}
Lastly, create the form using the Form component. A custom DatePickerField is used for the birthDate field. The form's initial values and submission handler are defined via the useForm hook.