Gallery permission
- React Native course
- Advanced
- Lesson 14/83
- 5 min
Learn to ask for gallery permission.
Gallery permission
Picking an image from the gallery requires asking the user for permission. expo-image-picker offers requestMediaLibraryPermissionsAsync. This function returns an object; if the status field is 'granted' the gallery is usable.
You make the permission request inside useEffect and write the result into state. State starts as null (not asked), then becomes true or false. This pattern is the most robust way to ask for permission when the app opens. If permission is denied the gallery button stays disabled.
Permission state
You keep the permission result in state: const [hasPermission, setHasPermission] = React.useState(null). The initial value null means 'not asked yet'. Inside useEffect you request the permission and write the result with setHasPermission(permission.status === 'granted').
During render you check three states: if null show 'Waiting for permission', if false show 'Permission needed', if true show the gallery button. While state is null the button stays disabled. This pattern gives meaningful feedback in every case.
Practice Request permission and write to state
Complete the empty useEffect. Call const permission = await ImagePicker.requestMediaLibraryPermissionsAsync(); write the result with setHasPermission(permission.status === 'granted'). The second argument of useEffect should be [].
Starter code
import React from 'react';
import * as ImagePicker from 'expo-image-picker';
export function useGalleryPermission() {
const [hasPermission, setHasPermission] = React.useState(null);
React.useEffect(() => {
// request permission and write the result
}, []);
return hasPermission;
}Sample solution
(async () => {
const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the permission function
const permission = await ImagePicker.____();
const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
Explanation: requestMediaLibraryPermissionsAsync asks for gallery permission.
2 Which field of the permission object is checked for 'granted'?
if (permission.??? === 'granted') { ... }- granted
- result
- allowed
- status Correct answer
Explanation: The status field carries the 'granted' value.
3 Match each state value to its meaning
| Term | Meaning |
|---|---|
null |
Waiting for permission |
true |
Gallery available |
false |
Permission denied |
'granted' |
status value |