| 2023-02-14

Creating a File Uploader in React with Vite

    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.

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

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

    cd src/components
    touch FileInput.jsx
    
    bash

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

    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;
    
    jsx

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

    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;
    
    jsx

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

    npm run dev
    
    bash

    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.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.