Installation
Install the Lit adapter for TanStack Form:Your First Form
The bare minimum to get started with TanStack Form is to create aTanStackFormController instance in your Lit component.
import { LitElement, html } from 'lit'
import { customElement } from 'lit/decorators.js'
import { TanStackFormController } from '@tanstack/lit-form'
@customElement('my-form')
export class MyForm extends LitElement {
#form = new TanStackFormController<Employee>(this, {
defaultValues: {
firstName: '',
lastName: '',
},
onSubmit({ value }) {
// Do something with form data
console.log(value)
},
})
}
Use the
field method to wire up form elements. The first parameter is FieldOptions and the second is a callback to render your element:render() {
return html`
<form
@submit=${(e: Event) => {
e.preventDefault()
e.stopPropagation()
this.#form.api.handleSubmit()
}}
>
${this.#form.field(
{
name: 'firstName',
validators: {
onChange: ({ value }) =>
value.length < 3 ? 'Not long enough' : undefined,
},
},
(field) => {
return html`
<div>
<label for="${field.name}">First Name</label>
<input
id="${field.name}"
type="text"
placeholder="First Name"
.value="${field.state.value}"
@blur="${() => field.handleBlur()}"
@input="${(e: Event) => {
const target = e.target as HTMLInputElement
field.handleChange(target.value)
}}"
/>
</div>
`
},
)}
<button type="submit">Submit</button>
</form>
`
}
Complete Example
Here’s a complete working example with two fields:Next Steps
Now that you have a basic form working, you can explore more advanced features:- Learn about Basic Concepts like field state and validation
- Implement Form Validation with custom validators or schema libraries
- Manage Array Fields for dynamic lists of items