Author

PinoyFreeCoder

Published

Sun Apr 07 2024

Type

Free

Download

Not Available

TypeScriptReact-CropperTypeScriptReact-Cropper

Share this Source Code

Share This Article

Welcome to our comprehensive tutorial on React Image Cropper Firebase Upload! In this in-depth guide, we'll walk you through the process of integrating a powerful image cropper into your React applications and seamlessly uploading cropped images to Firebase storage.

Full Tutorial

To learn more about the application watch the video below.

App.tsx code snippet

    
      import Cropper from "react-cropper";
      import "cropperjs/dist/cropper.css";
      import { useState } from "react";
      import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";
      import { projectStorage } from "./firebase/config";
  
      function App() {
        const [dataUrl, setDataUrl] = useState<string>(""); //cropped image
        const [cropper, setCropper] = useState<any>();
        const [image, setImage] = useState(""); // default image preview
  
        const changeHandler = (e: any) => {
          e.preventDefault();
          let files;
          if (e.dataTransfer) {
            files = e.dataTransfer.files;
          } else if (e.target) {
            files = e.target.files;
          }
          const reader = new FileReader();
          reader.onload = () => {
            setImage(reader.result as any);
          };
          reader.readAsDataURL(files[0]);
        };
  
        const getCrop = () => {
          if (cropper !== undefined) {
            setDataUrl(cropper.getCroppedCanvas().toDataURL());
          }
        };
  
        const UploadImage = async () => {
          const fileName = _cropped_png;
          const arr = dataUrl.split(",");
          if (arr.length < 2) {
            throw new Error("Invalid data url");
          }
  
          const mime = arr[0].match(/:(.*?);/);
          if (!mime) {
            throw new Error("Invalid data URL format");
          }
          const mimeType = mime[1];
          const bstr = atob(arr[1]);
          let n = bstr.length;
          const u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          const FinalFile = new File([u8arr], fileName, { type: mimeType });
          //upload to firebase storage
          await firebaseUpload(FinalFile);
        };
  
        const firebaseUpload = async (image: File): Promise<string | undefined> => {
          return new Promise<string | undefined>((resolve, reject) => {
            const storageRef = ref(projectStorage, "/croppedImages/image.name"); // directory where the image will be saved;
            const metaData = {
              contentType: image.type,
              contentDisposition: "inline",
            };
  
            const uploadTask = uploadBytesResumable(storageRef, image, metaData);
  
            uploadTask.on(
              "state_changed",
              (snapshot) => {
                const percent = Math.round(
                  (snapshot.bytesTransferred / snapshot.totalBytes) * 100
                );
                console.debug(percent); //can be used on percent upload indicators
              },
              (err) => {
                console.error(err);
                reject(err);
              },
              async () => {
                try {
                  const url = await getDownloadURL(uploadTask.snapshot.ref);
                  console.log(url);
                  if (url) {
                    resolve(url); // url can be saved into a database
                  }
                } catch (error) {
                  console.error(error);
                  reject(error);
                }
              }
            );
          });
        };
  
        return (
          <div style="display: flex; gap: 4px">
            <div>
              <Input type="file" onChange={changeHandler} />
              <Cropper
                src={image}
                initialAspectRatio={16 / 9}
                guides={false}
                responsive={true}
                onInitialized={(instance) => {
                  setCropper(instance);
                }}
              />
              <button type="button" onClick={getCrop}>
                Crop Image
              </button>
            </div>
            <div style="display: flex; flex-direction: column; gap: 4px">
              <h2>Preview</h2>
              <img width={"300px"} src={dataUrl} />
              <button type="button" onClick={UploadImage}>
                Upload Image
              </button>
            </div>
          </div>
        );
      }
  
      export default App;
    
  

Quick Actions

Technologies

TypeScript
React-Cropper

Featured Products

Discover amazing deals and products we recommend

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Sustainably sourced, chemical-free beans for a delightful brew. Packed With Rich Nutrients. Coffee drink with mangosteen, guyabano and acai berry!

View Product
Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

View Product
URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

The U.are.U 4500 Fingerprint Reader is a USB peripheral perfect for individual desk top users, as well as multiple users in shared environments. Its compact design conserves desk space in enterprises, and its professional, modern appearance looks elegant in point-of-sale environments.

View Product
ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN 1080P Webcam for PC Laptop Online Class Webcams HD USB Web Camera with Mic Live Steam

View Product
TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

After washing your hair, roll on your scalp or skin spot you want to grow hair and gently massage for 2-3 minutes, no need to wash out, oil-based easy to use, and visible results within 2-4 weeks (depending on the skin absorption)

View Product
NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

The F160 dual screen desktop monitor arm has a durable Gas-strut design to enable adjustment of your screen to your desired height and angle. This allows you to experience your interface from the best possible viewing angle. This design is particularly useful in a professional environment for collaborative work that requires multiple screens, or any space where you need to efficiently fit multiple screens. A gravity spring pivot joint design offers effortless titling to eliminate awkward positioning.

View Product
Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Make the most of play time with G203—a gaming mouse in a variety of vibrant colors. With LIGHTSYNC technology, a gaming-grade sensor and a classic 6-button design, you’ll light up your game and your desk

View Product
Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

【ADJUSTABLE CLAMP】Screw clamp is easy to remove and reattach, adjustable clamps securely onto desks up to 4cm/1.57inch thick and as narrow as 1.2cm/0.47inch for a near universal fit on most desks.

View Product
NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

Refresh with a delicious blend of all-natural green tea, lemon and cucumber extracts with NEW NESTEA CLEANSE! It's high in fiber which aids in digestion, and has no added table sugar. So go ahead -- start your wellness journey with NESTEA CLEANSE! Ang Gaan with NESTEA!

View Product
Page 1 of 9