Table of Contents
- 1 View File in Native File Viewer in React Native
- 2 Why Native File Viewer?
- 3 How to view any file in Native File Viewer?
- 4 React Native File Viewer Example Overview
- 5 To Make a React Native App
- 6 Installation of Dependency
- 7 Linking of Dependency
- 8 CocoaPods Installation
- 9 Code for React Native File Viewer
- 10 To Run the React Native App
- 11 Output Screenshots
View File in Native File Viewer in React Native
This is a React Native File Viewer Example to View Files in Native File Viewer. I hope you have seen Example of File Picker in React Native as this is an extended example. This example will cover how to pick any file from the file system and view that file in a native File Viewer. If you face any trouble in the file picking then you can see Filer Picker example as we are not going to cover that in detail. The main focus will be on file viewer.
Why Native File Viewer?
Here native file viewer means we are not going to view the file in our application instead we will pick the file from file picker and will pass the file URL to FileViewer
component provided by react-native-file-viewer
, this component will trigger the native iOS/Android file viewer to open the file.
For example,
- You have selected an Image then it will open it in an image viewer or if you have multiple options to view the image then you will be asked to select an application to view the image
- If you have selected any pdf then it will open any pdf reader from your device
- On selection of any video, it will trigger a video player of your device to play the video
This is the best way to view the file. I know many people will not agree with my words “the best way to view the file” but I personally feel
- It will reduce the hard work to create and manage a file viewer to support different type of files
- People are used to of native file viewers of their devices so it’s easy to view files in native file viewer
- Achieving all the functionalities to compete with native file viewer is very time taking
- Performance can also be a point, Many native file viewers already handle the caching and everything of the available images in the device.
I think I have cleared why I prefer the Native file viewer.
How to view any file in Native File Viewer?
To trigger any Native File Viewer from our app we are going to use FileViewer
component provided by react-native-file-viewer
. This is 2 step process
- First, we pick a file using any file picker or you can also take the path of any downloaded file. Here I am using react-native-document-picker for file picking
const res = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); singleFile = res;
- Now pass the file URI in FileViewer to open the file
let uri = singleFile.uri; if (Platform.OS === 'ios') { uri = res.uri.replace('file://', ''); } FileViewer.open(uri) .then(() => { //Can do anything you want after opening the file successfully console.log('Success'); }) .catch(_err => { //Handle failure here console.log(_err); });
Please note in case of iOS we need to remove the ‘file://’ prefix from the file path.
React Native File Viewer Example Overview
In this example, We are going to create one Screen with one button. On click of the button, we are going to trigger file picker and after selecting the file we will open the file in the native file viewer.
If you face any challenge with the file picker then you can see Example of File Picker in React Native it will help you to solve your problems. Now let’s get started with the Example.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
Now we need to install the dependencies which we require for this project. Open the terminal and jump into your project
cd ProjectName
For the file picker install react-native-document-picker
using the following command
npm install react-native-document-picker --save
Now we need to install react-native-file-viewer
from which we will import FileViewer
component. Please run the below command to install it
npm install react-native-file-viewer --save
Linking of Dependency
Now we need to link react-native-document-picker
, and react-native-file-viewer
using
react-native link react-native-document-picker
react-native link react-native-file-viewer
CocoaPods Installation
Now we need to install pods
cd ios && pod install && cd ..
Code for React Native File Viewer
Open App.js in any code editor and replace the code with the following code
App.js
// React Native File Viewer Example to View Files in Native File Viewer
// https://aboutreact.com/react-native-file-viewer/
// Import React
import React from 'react';
// Import core components
import {
StyleSheet,
View,
Text,
TouchableOpacity,
Platform,
} from 'react-native';
// Import File Viewer to View Files in Native File Viewer
import FileViewer from 'react-native-file-viewer';
// Import DocumentPicker to pick file to view
import DocumentPicker from 'react-native-document-picker';
const App = () => {
const selectOneFile = async () => {
// To Select File
try {
const res = await DocumentPicker.pick({
// Provide which type of file you want user to pick
type: [DocumentPicker.types.allFiles],
// There can me more options as well
// DocumentPicker.types.allFiles
// DocumentPicker.types.images
// DocumentPicker.types.plainText
// DocumentPicker.types.audio
// DocumentPicker.types.pdf
});
if (res) {
let uri = res.uri;
if (Platform.OS === 'ios') {
// Remove 'file://' from file path for FileViewer
uri = res.uri.replace('file://', '');
}
console.log('URI : ' + uri);
FileViewer.open(uri)
.then(() => {
// Do whatever you want
console.log('Success');
})
.catch(_err => {
// Do whatever you want
console.log(_err);
});
}
} catch (err) {
// Handling Exception
if (DocumentPicker.isCancel(err)) {
// If user canceled the document selection
alert('Canceled');
} else {
// For Unknown Error
alert('Unknown Error: ' + JSON.stringify(err));
throw err;
}
}
};
return (
<View style={styles.mainBody}>
<View style={{ alignItems: 'center' }}>
<Text
style={{
fontSize: 30,
textAlign: 'center'
}}>
Native file viewer for React Native
</Text>
<Text
style={{
fontSize: 25,
marginTop: 20,
textAlign: 'center'
}}>
Preview any type of file supported by the mobile device
</Text>
<Text
style={{
fontSize: 25,
marginTop: 20,
marginBottom: 30,
textAlign: 'center',
}}>
www.aboutreact.com
</Text>
</View>
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={selectOneFile}>
<Text style={styles.buttonTextStyle}>
Select File to View
</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
mainBody: {
flex: 1,
justifyContent: 'center',
padding: 20,
},
buttonStyle: {
backgroundColor: '#307ecc',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#307ecc',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 15,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Android
iOS
This is how you view files in React Native using Native File Viewer. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Hello Snehal
first of all this is good article, but it open with externally.
I have to open MS Excel, MS Word, And PDF in application in react native
for pdf I figure out below library
https://www.npmjs.com/package/react-native-pdf
Any Suggestion for open MS Excel, MS Word Internally in application.
Regards
Hardik