React Native File Viewer Example to View Files in Native File Viewer

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,

  1. 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
  2. If you have selected any pdf then it will open any pdf reader from your device
  3. 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

  1. It will reduce the hard work to create and manage a file viewer to support different type of files
  2. People are used to of native file viewers of their devices so it’s easy to view files in native file viewer
  3. Achieving all the functionalities to compete with native file viewer is very time taking
  4. 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

  1. 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],
    });
    this.setState({ singleFile: res });
  2. 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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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 () => {
    //handler 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') {
          //After picking the file we need to remove 'file://' from file path
          //Because FileViewer will not show the file with 'file://' prefix
          uri = res.uri.replace('file://', '');
        }
        console.log('URI : ' + uri);
        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);
          });
      }
    } catch (err) {
      //Handling any exception (If any)
      if (DocumentPicker.isCancel(err)) {
        //If user canceled the document selection
        alert('Canceled from single doc picker');
      } 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
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Android

File Viewer Example Android Screenshot 1   File Viewer Example Android Screenshot 2   File Viewer Example Android Screenshot 3   File Viewer Example Android Screenshot 4

iOS

File Viewer Example iOS Screenshot 1    

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. 🙂


Related Posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.