Skip to content

ServerlessReact.dev

Student Login
  • Intro
  • Project setup
  • Styling with TiaUI
  • Queries
  • Routing
  • Forms
  • Fin

Forms

At Tia we use react-hook-form to manage form state and a smattering of custom Form components to make life easier.

The main benefit of RHF is that it's built on uncontrolled components. No re-renders for every keypress 🤘

You shouldn't need to know details of RHF most of the time. The wiring is done for you inside TiaUI.

Read more about how it works in this article.

Basic use

A basic Tia form might look something like this:

function YayForm() {
// instantiates a form
const formMethods = useForm()
// what you wanna do with the data
function onSubmit(data) {
alert(JSON.stringify(data))
}
return (
// context provider + wiring
<Form onSubmit={onSubmit} useFormMethods={formMethods}>
{/* plain text fields */}
<Input name="firstName" />
<Input name="lastName" />
<Button type="submit">Click</Button>
</Form>
)
}

Exercise

No writable API for this workshop so we can't build a fancy form.

Create a form to filter your list of dog breeds. Render an input element and add a submit button.

You can use the useState hook to set a filter when the form submits. Another option is to watch the form value directly.

// with state
const [filter, setFilter] = useState("")
function filterBreeds(values: { filter: string }) {
setFilter(values.filter)
}
// live reading from form
const filter = formMethods.watch("filter")

Add staleTime: Infinity as a config to your breeds query to avoid refetching. Breeds don't change often.

Solution

You can find my solution at https://github.com/AskTia/tia-react-train/tree/solution-forms

Did you enjoy this chapter?

Previous:
Routing
Next:
Fin
Created bySwizecwith ❤️