Integrating Third-Party UI Components
Demonstrate how to integrate a third-party UI component (e.g., a date picker) into a form managed by TanStack Form, including custom validation.
import { useForm, Controller } from 'react-tanstack-form';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
function MyForm() {
const { control, handleSubmit } = useForm({
defaultValues: {
startDate: null,
},
});
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="startDate"
control={control}
rules={{ required: 'Start date is required' }}
render={({ field: { onChange, onBlur, value }, fieldState: { error } }) => (
<>
<DatePicker
selected={value}
onChange={onChange}
onBlur={onBlur}
placeholderText="Select a date"
/>
{error && <p>{error.message}</p>}
</>
)}
/>
<button type="submit">Submit</button>
</form>
);
}
This code demonstrates how to integrate a third-party UI component, specifically a date picker from 'react-datepicker', into a form controlled by TanStack Form. It uses the 'Controller' component from TanStack Form to manage the date picker's state and validation, ensuring the selected date follows the specified rules. The 'rules' prop applies a required validation, displaying an error message if no date is selected.