Initializing a Basic Form with TanStack
Showcase the initialization of a simple form using the TanStack library, highlighting the use of useForm hook to manage form state.
import { useForm } from '@tanstack/react-form';
Import useForm from TanStack's React form library.
function MyFormComponent() {
// Initialize the form with default values
const form = useForm({
defaultValues: {
firstName: '',
lastName: ''
},
onSubmit: async ({ values }) => alert(JSON.stringify(values))
});
Define a component and initialize the form with default values for firstName and lastName, and setup a simple onSubmit function that alerts the form values.
return (
<form onSubmit={form.handleSubmit}>
<div>
<label htmlFor='firstName'>First Name</label>
<input
id='firstName'
{...form.register('firstName')}
/>
</div>
<div>
<label htmlFor='lastName'>Last Name</label>
<input
id='lastName'
{...form.register('lastName')}
/>
</div>
<button type='submit'>Submit</button>
</form>
);
}
Return a form in the component's render function. Use form.register to bind input fields to the form state.
export default MyFormComponent;
Export the form component for use in your application.