Skip to content

Instantly share code, notes, and snippets.

@faustoct1
Last active August 19, 2025 21:19
Show Gist options
  • Save faustoct1/4697caa976d180d2170210692f9176d0 to your computer and use it in GitHub Desktop.
Save faustoct1/4697caa976d180d2170210692f9176d0 to your computer and use it in GitHub Desktop.
select photos and images anytime in your react native project
/*
this components requires you to use this expo components
- expo-media-library
- expo-image-picker
install them like:
yarn add expo-media-library expo-image-picker
or
npx expo install expo-media-library expo-image-picker
don't forget to run one of
- npx pod-install
- pod install
it also handles permissions properly
usage e.g.
<MediaPicker show={showMediaPicker} onFinish={async (uri)=>{
setShowMediaPicker(false) // you must need a showMediaPicker to set true/false to open close the media picker.
console.log(uri) // element selected in the media picker or array of uris if multi selection true
}} width={128} height={128} />
*/
import { useEffect } from 'react';
import { Linking, Dimensions, Alert } from 'react-native'
import * as ImagePicker from 'expo-image-picker'
import * as MediaLibrary from 'expo-media-library';
const {width:_width,height:_height} = Dimensions.get('window');
export default MediaPicker = ({show,onFinish,width,height,allowsMultipleSelection=0}) => {
//const [permissionResponse, requestPermission] = MediaLibrary.usePermissions();
useEffect(()=>{
if(show)onSelectImage()
return ()=> {}
},[show])
const selectImage = async(assets) =>{
if(onFinish){
onFinish( assets === null ? null : (allowsMultipleSelection ? assets.map(asset=>asset.uri) : assets[0].uri) )
}
}
const imagepicker = async () => {
const result = await ImagePicker.launchImageLibraryAsync({selectionLimit: allowsMultipleSelection, allowsMultipleSelection: !!allowsMultipleSelection, allowsEditing: !allowsMultipleSelection, aspect:[Math.round(width ? width : _width),Math.round(height ? height : _height)]});
selectImage(result.canceled ? null : result.assets)
}
const onSelectImage = async () => {
//const {status} = await Permissions.askAsync(Permissions.MEDIA_LIBRARY)
const {status} = await MediaLibrary.getPermissionsAsync()
let _status = status
if(status !== 'granted' && status !== 'denied'){
const {status} = await MediaLibrary.requestPermissionsAsync();
_status = status
}
if(_status === 'granted'){
imagepicker()
}else if(_status === 'denied'){
Alert.alert(
"<Your App Here> would like to access your image galery.",
' ',
[
{
text: "No",
onPress: () => {onClose()},
style: "cancel"
},
{ text: "Yes", onPress: () => {Linking.openSettings(); imagepicker()} }
],
{ cancelable: false }
)
}
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment