ReactNative app #5 : ImagePicker
Create reactNative React Image Picker
Load a local image
1
2
3
<Image source={require('./../../assets/images/placeholder.png')}
style=
/>
get expo image
https://docs.expo.dev/versions/latest/sdk/imagepicker/
npx expo install expo-image-picker
Add plugin in app.json
1
2
3
4
5
6
7
8
9
10
11
12
13
"web": {
"favicon": "./assets/favicon.png"
},
"plugins": [
[
"expo-image-picker",
{
"photosPermission": "The app accesses your photos to let you share them with your friends."
}
]
]
}
}
Implement ImagePicker
1
import * as ImagePicker from 'expo-image-picker';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default function AddPostScreen() {
const [image, setImage] = useState(null);
...
**const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.canceled) {
setImage(result.assets[0].uri);
}
};
return (
...**
Then download some images on your device or simulator. then replace a image that set by the picker.
1
2
3
4
5
6
7
8
9
10
{({handleChange,handleBlur,handleSubmit,values,setFieldValue})=>(
<View>
<TouchableOpacity onPress={pickImage}>
{image?
<Image source= style= />
:
<Image source={require('./../../assets/images/placeholder.png')}
style=
/>
}
update value for uri and validation.
- add new method
1
2
3
4
5
6
const onSubmitMethod=(value)=>{
value.image=image;
console.log(value);
}
return (
- change method into the Formik and add validation
1
2
3
4
5
6
7
8
9
10
11
12
13
<Formik
initialValues=
onSubmit={value=>onSubmitMethod(value)}
validate={(values)=>{
const errors={}
if(!values.title)
{
console.log("title is not present");
ToastAndroid.show("title must be there", ToastAndroid.SHORT)
errors.name="Title must be there"
}
return errors
}}
This post is licensed under CC BY 4.0 by the author.