Initializing a Form with useForm Hook
Demonstrate the basics of setting up a React form using TanStack Form's useForm hook, focusing on form registration and handling submit.
import { useForm } from '@tanstack/react-form';
First, import the useForm hook from TanStack Form.
function MyFormComponent() {
const form = useForm({
defaultValues: { firstName: '', lastName: '' },
onSubmit: async ({ values }) => {
alert(JSON.stringify(values, null, 2));
},
});
Initialize the form with useForm hook, setting default values and defining the onSubmit function.
return (
<div>
<form onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit();
}}>
<div>
<label htmlFor='firstName'>First name</label>
<input
id='firstName'
{...form.getFieldProps('firstName')}
placeholder='First name'
/>
</div>
<div>
<label htmlFor='lastName'>Last name</label>
<input
id='lastName'
{...form.getFieldProps('lastName')}
placeholder='Last name'
/>
</div>
<button type='submit'>Submit</button>
</form>
</div>
);
}
Render the form with input fields for firstName and lastName. Use getFieldProps to automatically handle registration and binding of the input elements.
export default MyFormComponent;
Export the form component.