Installation
Install the Svelte adapter for TanStack Form:Your First Form
The bare minimum to get started is to create a form and add a field usingcreateForm.
<script>
import { createForm } from '@tanstack/svelte-form'
const form = createForm(() => ({
defaultValues: {
fullName: '',
},
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
}))
</script>
The
createForm function returns a reactive form store that automatically updates your UI when form state changes.<form
onsubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
>
<!-- Fields will go here -->
</form>
Complete Example
Here’s a complete working form with validation:Example with Multiple Fields
Here’s a more complete example with multiple fields and validation:Key Concepts
Form Instance
The form instance returned bycreateForm is a reactive Svelte store that provides:
form.Field- Component for creating form fieldsform.Subscribe- Component for subscribing to form stateform.handleSubmit()- Method to submit the formform.reset()- Method to reset the form to default valuesform.useStore()- Hook to subscribe to specific form state
Field Component
Theform.Field component uses Svelte’s snippet syntax and provides:
field.state.value- Current field valuefield.handleChange()- Update field valuefield.handleBlur()- Mark field as blurredfield.state.meta- Field metadata (errors, touched, dirty, etc.)
Subscribe Component
Theform.Subscribe component lets you subscribe to specific form state to optimize rendering:
Next Steps
Now that you have a basic form working, explore more advanced features:- Learn about Basic Concepts like form options and field state
- Implement Form Validation with custom validators or schema libraries
- Manage Array Fields for dynamic lists of items