Accessing File Systems Using React Native FS

Learn via video courses
Topics Covered

Overview

Let's say you're building a note-taking app with React Native. You want to give users the ability to save their notes locally on their devices, so they can access them even if they don't have an internet connection.

By using React Native FS in this way, you're able to provide users with a reliable way to save and access their notes locally on their devices, even if they're offline.

What is react-native-fs?

React Native FS is a module or package in React Native that allows developers to interact with the file system on a mobile device using JavaScript

Getting Started with React Native FS

The react-native-fs module provides a simple way to access the file system on both Android and iOS devices. Here are the steps to get started:

  1. Install the react-native-fs module using npm or yarn. Run the following command in your React Native project directory:

    npm install react-native-fs

    or

    yarn add react-native-fs

  2. Link the module to your project using the react-native link.

    react-native link react-native-fs

    Done! No need to worry about manually adding the library to your project.

  3. Import the module into your React Native component where you want to use it.

    import RNFS from 'react-native-fs';

React Native FS Basic usage

Reading Directories

To read directories in React Native using the react-native-fs library, you can use the readdir or readDir method provided by the library.

The readdir method is used to read the contents of a directory and returns an array of file names in the directory.

Example:

Explanation:

We create a functional component named App that uses the useState hook to store an array of directory names in the state. In the useEffect hook, we call the readdir method on the RNFS object to get an array of directory names in the app's document directory.

We then set the directories state to this array of directory names. Finally, in the component's return statement, we render a View containing a text heading ("Directory List:") and a list of directory names rendered as Text components. We use the map method to iterate over the directories array in state and render a Text component for each directory name.

Example:

Explanation:

readDir is a method provided by the react-native-fs library, which allows you to read the contents of a directory in a more detailed manner. The readDir method returns an array of objects that contain information about each file or directory in the specified directory, including the file name, size, modification date, and type.

Getting Path Files

To get file paths using react-native-fs, you can use the following methods:

  1. RNFS.DocumentDirectoryPath: Returns the path to the app's documents directory. This is a good place to store files that should be backed up by iCloud or Google Drive.

    const documentsPath = RNFS.DocumentDirectoryPath;

  2. RNFS.CacheDirectoryPath: Returns the path to the app's cache directory. This directory should be used for files that can be recreated if deleted.

    const cachePath = RNFS.CacheDirectoryPath;

  3. RNFS.ExternalDirectoryPath: Returns the path to the primary external storage directory (such as an SD card). This directory is not available on all devices.(android only)

    const externalPath = RNFS.ExternalDirectoryPath;

  4. RNFS.ExternalStorageDirectoryPath: Returns the path to the primary external storage directory (such as an SD card). This directory is not available on all devices.(android only)

    const externalStoragePath = RNFS.ExternalStorageDirectoryPath;

  5. RNFS.TemporaryDirectoryPath: Returns the path to the app's temporary directory. This directory is cleared when the app is closed.

    const temporaryPath = RNFS.TemporaryDirectoryPath;

  6. PicturesDirectoryPath: Returns the path to the device's pictures directory.

    const picturesPath = RNFS.PicturesDirectoryPath;

  7. RNFS.DownloadDirectoryPath: Returns the path to the device's default download directory.(android only)

    const downloadPath = RNFS.DownloadDirectoryPath;

  8. RNFS.ExternalCachesDirectoryPath Returns the path to the external app cache directory on Android devices. This directory is used for storing cached files that are not critical and can be deleted when the device runs low on storage.(android only)

    const externalCachePath = RNFS.ExternalCachesDirectoryPath;

  9. RNFS.LibraryDirectoryPath Returns the path to the app's library directory on iOS devices. This directory is used for storing files that are not user-generated data, such as downloaded files, application support files, and cached data. (iOS only)

    const libraryPath = RNFS.LibraryDirectoryPath;

  10. RNFS.MainBundlePath is a method provided by react-native-fs that returns the path to the main bundle directory of the app. This directory contains the app's JavaScript code and assets, and it is read-only.(iOS only)

    const mainBundlePath = RNFS.MainBundlePath;

    If you need to access files on Android devices, you can use one of the other file system directories provided by react-native-fs, such as RNFS.DocumentDirectoryPath, RNFS.ExternalDirectoryPath, or RNFS.ExternalStorageDirectoryPath. These directories provide read-and-write access to different areas of the device's file system, depending on your app's needs in React Native FS.

Example:

Explanation:

We created several hooks for reading each directory path. And then we are presenting the path in the application in text format.

Advance Usage of React Native FS

Folder Creation

Example:

Explanation:

In this example, we're using useState to manage the folderName state, which is used to set the name of the folder, and the folders state, which is used to store the list of folder names. When the user clicks the "Create Folder" button, the handleCreateFolder function is called, which uses RNFS.mkdir to create the folder in the document directory using React Native FS.

After the component mounts, the useEffect hook is called to get a list of all the folders in the document directory using RNFS.readDir. We're filtering out all the non-directory items and only keeping the directory names, which are then set to the folder state using setFolders.

We're using a FlatList component to render the list of folders. The renderFolder function is used to render each item in the list, which is just a Text component displaying the folder name.

Note that you'll need to have the react-native-fs module installed in your project and imported at the top of your file. Also, remember to import the necessary components from React Native (View, TextInput, Button, Alert, FlatList, and Text) at the top of your file as well.

File Creation

Example:

Explanation:

In this example, we're using useState to manage the fileName state, which is used to set the name of the file, and the file state, which is used to store the list of file names. When the user clicks the "Create File" button, the handleCreateFile function is called, which uses RNFS.writeFile to create an empty file with the given name and .txt extension in the document directory using React Native FS.

After the component mounts, the useEffect hook is called to get a list of all the files in the document directory using RNFS.readDir present in React Native FS. We're filtering out all the non-file items and only keeping the file names, which are then set to the files state using setFiles.

We're using a FlatList component to render the list of files. The renderFile function is used to render each item in the list, which is just a Text component displaying the file name.

Reading Files

Explanation:

In React Native FS,we're using useState to manage the fileName state, which is used to set the name of the file, and the fileContent state, which is used to store the contents of the file. When the user clicks the "Read File" button, the handleReadFile function is called, which uses RNFS.readFile to read the contents of the file with the given name and .txt extension in the document directory.

If the file is read successfully, the contents are set to the fileContent state using setFileContent. We're using a conditional rendering to display the contents of the file as a Text component if the fileContent state is not empty.

Deleting Files

Example:

Explanation:

handleDeleteFile function is called, which uses RNFS.unlink to delete the file with the given name and .txt extension in the document directory. If the file is deleted successfully, the handleDeleteFile function uses RNFS.readDir to get a list of the remaining files in the document directory and sets the remainingFiles state to an array of the names of those files.

Complete React Native FS Example

Example:

Explanation:

In this final section of React Native FS, we are using four useState for managing to create and delete files and folders in a directory. To manage all side effects we used the useEffect hook for all individual states. And in the end, we are showing the present files and folders name.

Output:

output

Conclusion

  1. Overall, React Native FS is an essential tool for any React Native developer looking to incorporate file management capabilities into their applications.
  2. Its ease of use, efficiency, and wide range of features make it a valuable asset in building high-quality and robust mobile applications.