OWolf

2024-09-09 web, development, javascript

Creating a File Uploader in React with Vite

By O. Wolfson

In this tutorial, you will learn how to use Vite to create a file uploader app using React. Vite is a build tool that allows for fast development and hot module replacement. It is easy to set up and supports a wide range of front-end frameworks, including React.

Tutorial

Create a new React project using Vite.

bash
mkdir file-uploader
cd file-uploader
npm init vite@latest
# Select "react" for framework, "js" for language, and "y" for install dependencies

Create a new component called "FileInput.jsx". This component will be responsible for handling file input and uploading.

bash
cd src/components
touch FileInput.jsx

Import the necessary dependencies, including React, useState hook, and axios library. Update the FileInput.jsx file with the following code:

jsx
import React, { useState } from "react";

const FileInput = () => {
  const [file, setFile] = useState(null);
  const [url, setUrl] = useState(null);

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

  const handleFileUpload = () => {
    if (!file) {
      alert("Please select a file.");
      return;
    }

    // Add code to upload file here

    console.log(file);
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleFileUpload}>Upload File</button>
      {url && (
        <p>
          Uploaded file URL: <a href={url}>{url}</a>
        </p>
      )}
    </div>
  );
};

export default FileInput;

Render the FileInput component in App.jsx. Update the App.jsx file with the following code:

jsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
import Button from "./components/Button";
import FileInput from "./components/FileInput";

function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <div>
        <FileInput />
      </div>
    </div>
  );
}

export default App;

Run the Vite development server and test the file uploader app.

bash
npm run dev

Open http://localhost:3000 in your web browser. When you select a file and click the "Upload File" button, it should log the selected file to the console.

Conclusion

That's it! With Vite, it is easy to set up a fast and efficient development environment for your React project. The FileInput component provides a simple and intuitive file uploader that can be customized to fit your needs.