Search code examples
react-nativeelementavatarreact-native-image-picker

react-native-elementes Avatar


I'd like to upload an image by clicking on avatar component and then pick a picture from the device. Anyone knows if its possible using avatar component from react-native-elements?

I have already added the permissons below:

 <uses-permission android:name="android.permission.CAMERA" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Do you think I have to install the react-native-image-picker library as well?

Thanks in advance,


Solution

  •   constructor(props: Object) {
        super(props);
        this.state = {
          image_uri: '' //initially set the state of image with default image
        };
      }
    
    **your avatar component** 
    
      <Avatar
        small
        rounded
        source = {{uri: this.state.image_uri}}
        onPress={() => this.openImagePicker()}
        activeOpacity={0.7}
      />
    
     **import { showImagePicker } from 'react-native-image-picker';**
    
      captureMediaOrGetFromDeviceLibrary(options: Object = OPTIONS) {
          var promise = new Promise(function(fulfill, reject) {
          showImagePicker(options, (response) => {
          if (response.didCancel) {
            fulfill ({success: false})
          } else if (response.error) {
            fulfill ({success: false})
          } else {
            fulfill ({
             success: true,
             media_data: response
            })
          }
        })
      })
      return promise.then((response)=>{
        return response
      })
     }
    
    
     openImagePicker() {
       const options = {
        quality: 1.0,
        maxWidth: 500,
        maxHeight: 500
       };
       return captureMediaOrGetFromDeviceLibrary(options).then((response)=> {
         if(response.success){
           this.setState({image_uri:response.media_data.uri})
         }
       }) 
      }
    }