Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

react-native.md

57 lines1.5 KB

1---
2id: react-native
3title: Usage with React Native
4---
5​
6TanStack Form is headless, so React Native uses the same form and validation
7APIs. Connect the field handlers to the props exposed by native controls.
8​
9```tsx
10import { Button, Text, TextInput, View } from 'react-native'
11import { useForm } from '@tanstack/react-form'
12​
13export function AccountForm() {
14 const form = useForm({
15 defaultValues: { age: '' },
16 onSubmit: ({ value }) => console.log(value),
17 })
18​
19 return (
20 <View>
21 <form.Field
22 name="age"
23 validators={[
24 {
25 triggers: ['change', 'blur'],
26 run: ({ value }) =>
27 Number(value) >= 13 ? undefined : 'You must be at least 13',
28 },
29 ]}
30 >
31 {(field) => (
32 <View>
33 <Text>Age</Text>
34 <TextInput
35 value={field.value}
36 keyboardType="number-pad"
37 onBlur={field.handleBlur}
38 onChangeText={field.handleChange}
39 />
40 {field.errors.map((error) => (
41 <Text key={error.message} accessibilityRole="alert">
42 {error.message}
43 </Text>
44 ))}
45 </View>
46 )}
47 </form.Field>
48​
49 <Button title="Submit" onPress={() => void form.handleSubmit()} />
50 </View>
51 )
53```
54​
55React Native has no DOM form submission or `querySelector`. Call
56`form.handleSubmit()` from a button and keep refs to native inputs when you need
57to focus an invalid field.