In today’s digital world, file sharing is a common requirement, and building a file-sharing app is an excellent project to improve your web development skills. This tutorial will guide you through creating a simple file-sharing application using React.js. By the end of this tutorial, you will have a basic file-sharing app where users can upload files and generate shareable links to download them.

Project Overview

Features:

  1. Upload files using a drag-and-drop interface or a file selection dialog.
  2. Generate a unique link for each uploaded file.
  3. Provide a download option for users with the link.

Tools and Libraries Used

  • React.js: For building the user interface.
  • Firebase: For storing files and generating download links.
  • Bootstrap: For styling and layout.

Step 1: Setting Up the Project

First, make sure you have Node.js installed on your machine. You can check by running the following command:

				
					node -v
				
			

If Node.js is not installed, download and install it from nodejs.org.

Now, let’s create a new React project using the Create React App tool. Open your terminal and run:

				
					npx create-react-app file-sharing-app
				
			

This command will create a new directory named file-sharing-app with a basic React setup.

Step 2: Installing Firebase

We will use Firebase to handle file storage and generate download links. Install the Firebase SDK by navigating to your project directory and running:

				
					cd file-sharing-app
npm install firebase
				
			

Step 3: Configuring Firebase

  1. Go to the Firebase Console and create a new project.
  2. Once your project is set up, click on the Web icon to create a new web app in Firebase.
  3. Firebase will provide a configuration object. Keep it handy as we will need it in our React project.

Create a file named firebase.js in your src directory and add your Firebase configuration to it:

				
					// src/firebase.js

import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";

// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);

export { storage };
				
			

Replace the placeholders (like YOUR_API_KEY) with your actual Firebase project credentials.

Step 4: Creating the File Upload Component

Let’s create a React component that will allow users to upload files. Create a new file named FileUpload.js in the src directory:

				
					// src/FileUpload.js

import React, { useState } from 'react';
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { storage } from './firebase';

function FileUpload() {
    const [file, setFile] = useState(null);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [downloadURL, setDownloadURL] = useState('');

    const handleFileChange = (e) => {
        setFile(e.target.files[0]);
    };

    const handleUpload = () => {
        if (file) {
            const storageRef = ref(storage, `files/${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on(
                'state_changed',
                (snapshot) => {
                    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    setUploadProgress(progress);
                },
                (error) => {
                    console.error("Upload failed", error);
                },
                () => {
                    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                        setDownloadURL(downloadURL);
                    });
                }
            );
        }
    };

    return (
        <div className="file-upload">
            <input type="file" onChange={handleFileChange} />
            <button onClick={handleUpload}>Upload</button>
            <progress value={uploadProgress} max="100" />
            {downloadURL && (
                <div>
                    <p>File uploaded successfully!</p>
                    <a href={downloadURL} target="_blank" rel="noopener noreferrer">Download File</a>
                </div>
            )}
        </div>
    );
}

export default FileUpload;
				
			

Step 5: Adding Styling with Bootstrap

To make the app look better, let’s add some basic styling using Bootstrap. Install Bootstrap by running:

				
					npm install bootstrap
				
			

Import Bootstrap in your index.js file:

				
					// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
);
				
			

Now, you can use Bootstrap classes in your FileUpload component for styling.

Step 6: Creating the Main App Component

Update the App.js file to include the FileUpload component:

				
					// src/App.js

import React from 'react';
import FileUpload from './FileUpload';

function App() {
    return (
        <div className="App">
            <header className="App-header">
                <h1>Simple File Sharing App</h1>
            </header>
            <main>
                <FileUpload />
            </main>
        </div>
    );
}

export default App;
				
			

Step 7: Running the File Sharing App

  • Save all your files and make sure your Firebase project is properly configured.

  • In your terminal, navigate to the project directory and run:

				
					npm start
				
			
  • This will start the development server and open the file-sharing app in your default web browser.

 

Explanation of the Code

  1. Firebase Initialization: We configured Firebase using the firebase.js file to connect to our Firebase project and use Firebase storage.
  2. File Upload Component: The FileUpload.js component handles file selection, uploads the file to Firebase storage, and tracks the upload progress. Once the file is uploaded, it generates a download link using getDownloadURL().
  3. Styling: We used Bootstrap to style the app, making it responsive and visually appealing.

Additional Features

To make this app more robust and production-ready, consider adding the following features:

  • Authentication: Use Firebase Authentication to allow users to log in and keep track of their uploaded files.
  • File List: Display a list of all uploaded files with options to delete or rename them.
  • Expiration: Implement an expiration time for the download links to enhance security.

Conclusion

Congratulations! You’ve built a basic file-sharing app using React.js and Firebase. This project demonstrates how to integrate cloud storage with a web application using Firebase and React. Feel free to enhance this app by adding more features and improving the UI. Happy coding!