Home » React / Dropzone / Axios

Install React

What is React? React is a JavaScript library for building user interfaces. It was developed by Facebook and is widely used for building single-page applications where the UI needs to be responsive and dynamic. React allows developers to create reusable UI components, making it easier to manage and update complex user interfaces.


Key Concepts in React:

  1. Components: React applications are built using components, which are self-contained, reusable pieces of code responsible for rendering a part of the UI.
  2. Virtual DOM: React uses a virtual DOM to improve performance by updating only the parts of the actual DOM that have changed.

Run npx create-react-app <projectName>

Run cd <projectName>

Run npm start

    Starts the development server.

Integrated Terminal CTRL+C and Y to confirm to stop app

  npm run build

    Bundles the app into static files for production.

  npm test

    Starts the test runner.

  npm run eject

    Removes this tool and copies build dependencies, configuration files

    and scripts into the app directory. If you do this, you can’t go back!

npm start to run


NPX update Commands

npx browserslist@latest –update-db

npx create-react-app “./” for current file or “/namefile”

Install React Router using command:

npm install react-router-dom@latest

To start a new Create React App project with TypeScript, you can run:

npx create-react-app my-app –template typescript

To add TypeScript to an existing Create React App project, first install it:

npm install –save typescript @types/node @types/react @types/react-dom @types/jest


Bootstrap

https://getbootstrap.com/ > Read the Docs

https://getbootstrap.com/docs/5.3/getting-started/introduction/

include Bootstraps CSS and JS

<!doctype html>

<html lang="en">

  <head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap demo</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

  </head>

  <body>

    <h1>Hello, world!</h1>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

  </body>

</html>

React Hooks

useState -takes an  initial value and returns a state variable and a method for updating that variable.

useEffect -adds ability to perform side effects from a function. Lets you call a function when lifecycle events happen

Rules of Hooks

Must be called at the top level (not inside loops, conditions, or nested functions).

Only be called from function components.

Hooks start with “use” by convention. (Although not a Rule)

useState

import React, {useState} from ‘react’;

function Example() {

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

return (

<div>

  <p> You clicked {count} times </p>

  <button onClick={(() => setCount(count + 1)}>

    Click me

   </button>

</div>

);

}

useEffect

(Adds ability to perform side effects from a function component. By default, React runs effects after every render, including the first.)

e.g.,

function LifecycleDemo() {

   useEffect(() => {

   console.log(‘render!’);

  return () = > console.log(‘unmounting’);

  })

Return “This is a lifecycle demo”;

—-

When does useEffect run?

By default: before every render. If want to run it less often provide a 2nd argument

*Array /

*If one of them has changed, the effect will run again./

*Will still run after the initial render. /

*To run only on Mount (loading) and unmount (unloading), pass and empty array {[]}

Uses for useEffect

       -Fetch initial data.

       -Focus inputs on first render.

       – re-fetching when data changes.

What are Hooks?

Functions that let you hook into React state and lifecycle features from function components.

Hooks allow you to reuse stateful logic.

Custom Hooks

  • A JavaScript function whose name starts with “use” and that may call other Hooks.
  • Lets you extract component logic into reusable functions.
  • Isn’t a feature of React, but is enabled by Hooks.

Why use Custom Hooks

  • Share logic between components.
  • Hide complex logic behind a simple interface.

React Hooks API documentation.

React limits the number of renders to prevent an infinite loop.


Dropzone:

What is Dropzone? Dropzone is a popular open-source library for handling file uploads in web applications. It provides an easy and customizable way to allow users to drag and drop files into an area, or select files using a file dialog.

Key Features of Dropzone:

  1. Drag-and-Drop: Users can drag files from their computer and drop them onto a designated area in the web application.
  2. File Input: Users can also use a file input dialog to select files for upload.
  3. Preview: Dropzone often includes a file preview feature, allowing users to see a thumbnail or other information about the files they have selected.

To add/attach files to web app.

url: https://github.com/react-dropzone/react-dropzone

install: npm install –save react-dropzone  <-command

Axios

What is Axios? Axios is a popular JavaScript library for making HTTP requests. It can be used both in the browser and in Node.js environments. Axios simplifies the process of making asynchronous HTTP requests and handling responses.

Key Features of Axios:

  1. Promise-based: Axios uses promises, making it easy to handle asynchronous operations and providing a clean syntax for chaining actions after the request is complete.
  2. Interceptors: Axios allows you to intercept requests or responses before they are handled by then or catch. This is useful for tasks like adding headers to requests or handling errors globally.
  3. Support for JSON Data: Axios automatically parses JSON responses, making it convenient when working with APIs that return JSON data.

In a React application, you might use Dropzone to handle file uploads within a specific component. When a user interacts with Dropzone to select or drop files, you can use Axios to send those files to a server for processing (e.g., storing in a database or performing some other server-side operation). Axios helps make the HTTP request to the server to handle the file upload, and you can use React state and lifecycle methods to manage the UI and handle the response from the server.

Allows to send html requests to the backend.

Cd inside project: project/src/main/frontend

npm -S i axios        <-command to install axios “i” means install

To download the axios library in VS code.

Add IMPORTS to App.js:

Import Reach, {useState, useEffect} from “react”;

Import axios from “axios”;

Here’s a simplified example of how you might use Dropzone and Axios together in a React component:

import React, { useState } from 'react';
import Dropzone from 'react-dropzone';
import axios from 'axios';
import 'react-dropzone-uploader/dist/styles.css'; // Add this line if you're using react-dropzone-uploader

// Add any additional import statements for styling or other dependencies you may have


const FileUploadComponent = () => {
  const [uploadedFiles, setUploadedFiles] = useState([]);

  const onDrop = async (acceptedFiles) => {
    const formData = new FormData();
    acceptedFiles.forEach((file) => {
      formData.append('files', file);
    });

    try {
      const response = await axios.post('/upload', formData);
      console.log('Server Response:', response.data);

      // Update state with the uploaded files
      setUploadedFiles([...uploadedFiles, ...response.data.files]);
    } catch (error) {
      console.error('Error uploading files:', error);
    }
  };

  return (
    <div>
      <Dropzone onDrop={onDrop}>
        {({ getRootProps, getInputProps }) => (
          <div {...getRootProps()}>
            <input {...getInputProps()} />
            <p>Drag and drop files here, or click to select files</p>
          </div>
        )}
      </Dropzone>

      {/* Display a list of uploaded files */}
      <ul>
        {uploadedFiles.map((file, index) => (
          <li key={index}>{file.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default FileUploadComponent;

Proudly powered by WordPress