Horje
Create File Explorer App using React-Native

Creating a File Explorer app using React Native provides a seamless way to explore and interact with the device’s file system on both iOS and Android platforms. In this tutorial, we’ll guide you through the process of building a simple yet functional File Explorer app.

Output Preview:

Screenshot-2024-01-15-171836

Prerequisites:

Approach to create File Explorer:

  • Setup: Initialize a React Native project.
  • Navigation: Use @react-navigation for navigation. Configure navigation with createStackNavigator in App.js.
  • UI Components: Create Directory and File components for representation.
  • Screen Implementation: Develop FileExplorerScreen.js for displaying directories and files. Implement logic for user interactions.
  • Connect Screen: Integrate FileExplorerScreen into navigation in App.js.

Steps to Create the Project:

Step 1: Create a new React Native project

npx react-native init FileExplorerApp
cd FileExplorerApp

Step 2: Install React Native FS:

npm install react-native-fs

Project Structure:Screenshot-2024-01-15-173447

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "18.2.0",
"react-native": "0.73.2",
"react-native-fs": "^2.20.0",
"react-navigation": "^4.4.4",
"react-navigation-stack": "^2.10.4"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0",
"@react-native/babel-preset": "0.73.19",
"@react-native/eslint-config": "0.73.2",
"@react-native/metro-config": "0.73.3",
"@react-native/typescript-config": "0.73.1",
"@types/react": "^18.2.6",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.6.3",
"eslint": "^8.19.0",
"jest": "^29.6.3",
"prettier": "2.8.8",
"react-test-renderer": "18.2.0",
"typescript": "5.0.4"
}

Step 3: Create the required file and add the following code.

JavaScript
// FileList.js

import React from "react";
import { View, Text, FlatList, TouchableOpacity, Image } from "react-native";

const FileList = ({ files, onFilePress }) => {
    return (
        <FlatList
            data={files}
            keyExtractor={(item) => item.path}
            renderItem={({ item }) => (
                <TouchableOpacity onPress={() => onFilePress(item)}>
                    <View
                        style={{
                            flexDirection: "row",
                            alignItems: "center",
                            padding: 10,
                            borderBottomWidth: 1,
                            borderBottomColor: "#ccc",
                        }}
                    >
                        <Image
                            source={
                                item.isDirectory()
? require("https://media.geeksforgeeks.org/wp-content/uploads/20240116233908/icons8-folder.gif")
: require("https://media.geeksforgeeks.org/wp-content/uploads/20240116233844/file.gif")
                            }
                            style={{ width: 24, height: 24, marginRight: 10 }}
                        />
                        <Text>{item.name}</Text>
                    </View>
                </TouchableOpacity>
            )}
        />
    );
};

export default FileList;
JavaScript
// FileExplorer.js

import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, Image, StyleSheet } from 'react-native';
import FileList from './FileList';
import RNFS from 'react-native-fs';

const FileExplorer = () => {
    const [currentPath, setCurrentPath] = useState(RNFS.ExternalStorageDirectoryPath);
    const [files, setFiles] = useState([]);

    useEffect(() => {
        loadFiles(currentPath);
    }, [currentPath]);

    const loadFiles = async (path) => {
        try {
            const result = await RNFS.readDir(path);
            setFiles(result);
        } catch (error) {
            console.error('Error reading directory:', error);
        }
    };

    const handleFilePress = (file) => {
        if (file.isDirectory()) {
            setCurrentPath(file.path);
        } else {
            console.log('File pressed:', file);
            // Add your logic to open/view the file
        }
    };

    const navigateUp = () => {
        const parts = currentPath.split('/');
        parts.pop(); // Remove the last part to go up one level

        // Join the parts back together to form the new path
        const parentPath = parts.join('/');

        setCurrentPath(parentPath);
    };

    return (
        <View style={styles.container}>
            <Text style={styles.title}>File Explorer</Text>
            <View style={styles.pathContainer}>
                <TouchableOpacity onPress={navigateUp} disabled={currentPath === RNFS.ExternalStorageDirectoryPath}>
                    <Image source={require('https://media.geeksforgeeks.org/wp-content/uploads/20240116233844/back_icon.gif')} 
                        style={styles.backIcon} />
                </TouchableOpacity>
                <Text style={styles.path}>{currentPath}</Text>
            </View>
            <FileList files={files} onFilePress={handleFilePress} />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 30,
        backgroundColor: '#f0f0f0',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
        marginBottom: 10,
    },
    pathContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    backIcon: {
        width: 24,
        height: 24,
        marginRight: 10,
    },
    path: {
        fontSize: 16,
    },
});

export default FileExplorer;
JavaScript
//App.js

import React from 'react';
import { View } from 'react-native';
import FileExplorer from './FileExplorer';

const App = () => {
    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <FileExplorer />
        </View>
    );
};

export default App;

Step 4: To start the application run the following command.

  • Run the app on Android
npx react-native run-android
  • Run the app on iOS
npx react-native run-ios

Output:




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Chakra UI Feedback Spinner Chakra UI Feedback Spinner
Chakra UI Feedback Circular Progress Chakra UI Feedback Circular Progress
Chakra UI Layout, width and height Chakra UI Layout, width and height
Use of the Ternary Operator in Conditional Rendering. Use of the Ternary Operator in Conditional Rendering.
What Are YouTube Channel Memberships And How To Start It What Are YouTube Channel Memberships And How To Start It

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11