How to use Image Picker in React Native

How to use Image Picker in React Native



we will go through step by step from install react native project to upload image to php server.

Open terminal and run a command to install react native project:
react-native init ProjectName

Now time to install library: cd to your ProjectName in
terminal, and run below command:
npm install react-native-image-picker --save
we are using here react native library that allow you to select media from device library. with help of this library you can use images direct from camera. 


Camera Permission Setting:

we need to set permission to use the camera for android. open AndroidManifest.xml from project folder. and line for camera permission.

Write Storage Permission:
same camera permissions we have to set storage permission to Read and Write the content in the SD card.

Now it's time to code: 
Open App.js in any code editor and replace the code with the following code:
import ImagePicker from 'react-native-image-picker'
add now options for camera:
const options={
title: 'my pic app',
takePhotoButtonTitle: 'Take photo with your camera',
chooseFromLibraryButtonTitle: 'Choose photo from library',
}

Constructor Function:
constructor(props){
super(props);
this.state={
avatarSource: null,
pic:null
}
}

Button for select image:
<TouchableOpacity style={{backgroundColor:'green',margin:10,padding:10}}
onPress={this.myfun}>
<Text style={{color:'#fff'}}>Select Image</Text>
</TouchableOpacity>

Now declare function to access this button:
myfun=()=>{
//alert('clicked');
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('Image Picker Error: ', response.error);
}
else {
let source = { uri: response.uri };
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
pic:response.data
});
}
});
}

Now we need view for display image(which we selected):
<Image source={this.state.avatarSource} style={{width:'100%',height:300,margin:10}}/>

Video tutorial: