ReactNative app #4 : Formik and Picker to add post
When it comes to creating forms in React Native applications, managing state and user input can be a complex task. Luckily, libraries like Formik provide a convenient way to handle form logic and validation. In this article, we’ll explore how to integrate Formik into a React Native application to create a dynamic form with a category picker.
- Setting Up Formik
Go to formik.org
install Formik
npm install formik --save
- AddPostScreen.jsx → return ()
1
import { Formik } from 'formik';
- Implementing the Form
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
**return (
<View className="p-10">
<Formik
initialValues=
onSubmit={value=>console.log(value)}
>
{({handleChange,handleBlur,handleSubmit,values})=>(
<View>
<TextInput
style={styles.input}
placeholder='Title'
value={values?.title}
onChangeText={handleChange('title')}
/>
<TextInput
style={styles.input}
placeholder='Description'
value={values?.desc}
numberOfLines={5}
onChangeText={handleChange('desc')}
/>
<TextInput
style={styles.input}
placeholder='Price'
value={values?.price}
keyboardType='number-pad'
onChangeText={handleChange('price')}
/>
{/* Category */}
<Button onPress={handleSubmit}
className="mt-7"
title="submit" />
</View>
)}
</Formik>
</View>
)
}**
Adding a Category Picker
https://docs.expo.dev/versions/latest/sdk/picker/
install the dependency
npx expo install @react-native-picker/picker
1
import {Picker} from '@react-native-picker/picker';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<Formik
initialValues=
onSubmit={value=>console.log(value)}
>
{({handleChange,handleBlur,handleSubmit,values,setFieldValue})=>(
{/* Category */}
<View style=>
<Picker
selectedValue={values?.category}
className="border-2"
onValueChange={itemValue=>setFieldValue('category', itemValue)}
>
{categoryList.length>0&&categoryList?.map((item,index)=>(
<Picker.Item key={index}
label={item?.name} value={item?.name} />
))}
</Picker>
</View>
This post is licensed under CC BY 4.0 by the author.