1 | initial version |
To enable users to provide file inputs or to upload files in React Native, we can use the react-native-document-picker
library.
Here are the steps to follow:
Install react-native-document-picker
by running the following command:
npm install react-native-document-picker
Import the library in your component:
import DocumentPicker from 'react-native-document-picker';
Add a button or any other UI element to trigger the file picker:
<Button title="Select File" onPress={selectFile} />
In the selectFile
function, call the DocumentPicker.pick
method to open the file picker and let the user select a file:
async function selectFile() {
try {
const result = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
});
// Handle the selected file
} catch (err) {
// Handle the error
}
}
Note that you can pass the type
option to restrict the types of files that the user can select.
Once the user selects a file, you can handle the selected file in the result
object. The result
object will contain information about the selected file, such as its URI, name, size, and type.
console.log(result.uri);
console.log(result.name);
console.log(result.size);
console.log(result.type);
You can then use this information to display the selected file or to upload it to a server.