🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

react-photo-editor

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-photo-editor

React component and hook for image editing, offering controls for brightness, contrast, saturation, and grayscale, along with features to rotate, flip, pan, draw, and zoom photos.

3.0.0
latest
Version published
Maintainers
1
Created

react-photo-editor

react-photo-editor

NPM Version NPM Downloads Bundle Size License

React component and hook for image editing with options to set brightness, contrast, saturation, and grayscale. Also with features to rotate, flip, pan, draw and zoom the photo.

📋 Table of Contents

✨ Features

  • 🎨 Color adjustments: Brightness, contrast, saturation, and grayscale
  • 🔄 Image manipulation: Rotate and flip (horizontal/vertical)
  • 🔍 Interactive control: Pan and zoom functionality
  • ✏️ Drawing tools: Draw directly on canvas
  • 🧩 Flexible integration: Use as a component or with the usePhotoEditor hook
  • 🎯 Highly customizable: Configurable UI, labels, and functionality

📦 Installation

Choose your preferred package manager:

# Using npm
npm install react-photo-editor

# Using yarn
yarn add react-photo-editor

🚀 Quick Start

import { useState } from 'react';
import { ReactPhotoEditor } from 'react-photo-editor';

function App() {
  const [file, setFile] = useState();
  const [showModal, setShowModal] = useState(false);

  // Show modal if file is selected
  const showModalHandler = () => {
    if (file) {
      setShowModal(true);
    }
  };

  // Hide modal
  const hideModal = () => {
    setShowModal(false);
  };

  // Save edited image
  const handleSaveImage = (editedFile) => {
    setFile(editedFile);
    // Do something with the edited file
  };

  const setFileData = (e) => {
    if (e?.target?.files && e.target.files.length > 0) {
      setFile(e.target.files[0]);
    }
  };

  return (
    <>
      <input type='file' onChange={(e) => setFileData(e)} multiple={false} />

      <button onClick={showModalHandler}>Edit Photo</button>

      <ReactPhotoEditor
        open={showModal}
        onClose={hideModal}
        file={file}
        onSaveImage={handleSaveImage}
      />
    </>
  );
}

export default App;

📱 Live Demo

See it in action on Stackblitz

⚠️ Migration Guide

Migrating from v2.x to v3.0.0

Breaking Changes

  • CSS Import Removed: The CSS file import (import 'react-photo-editor/dist/style.css') is no longer required
  • Tailwind CSS Configuration: No longer need to add './node_modules/react-photo-editor/dist/*.js' to your Tailwind config
  • Changed canvas class name and id: The class name and id for the canvas element have been changed from canvas to rpe-canvas for better consistency with the rest of the project. Make sure to update your usage accordingly.

🛠️ Configuration Options

The ReactPhotoEditor component accepts the following props:

PropTypeDefaultDescription
fileFile | undefinedRequiredThe input image file to be edited
allowColorEditingbooleantrueWhether to allow color editing options
allowRotatebooleantrueWhether to allow rotation of the image
allowFlipbooleantrueWhether to allow flipping of the image
allowZoombooleantrueWhether to allow zooming of the image
allowDrawingbooleantrueWhether to enable drawing options
downloadOnSavebooleanfalseWhether to enable downloading the edited image upon saving
openbooleanfalseWhether the photo editor modal is open
onClose() => void-Function invoked when the modal is closed
onSaveImage(image: File) => voidRequiredFunction invoked when the edited image is saved
modalHeightnumber | string'38rem'Height of the photo editor modal
modalWidthnumber | string'40rem'Width of the photo editor modal
canvasWidthnumber | string'auto'Width of the canvas element
canvasHeightnumber | string'auto'Height of the canvas element
maxCanvasHeightnumber | string'22rem'Maximum height of the canvas element
maxCanvasWidthnumber | string'36rem'Maximum width of the canvas element
labelsReactPhotoEditorTranslations-Custom labels for UI elements

🧰 Advanced Usage: Custom Component with usePhotoEditor Hook

For more control over the UI and functionality, you can use the usePhotoEditor hook to build your own custom editor component.

For full examples, see the example folder.

import { usePhotoEditor } from 'react-photo-editor';

function CustomPhotoEditor({ file }) {
  const {
    canvasRef,
    brightness,
    contrast,
    saturate,
    grayscale,
    setBrightness,
    setContrast,
    setSaturate,
    setGrayscale,
    handleZoomIn,
    handleZoomOut,
    generateEditedFile,
    resetFilters,
  } = usePhotoEditor({
    file,
    defaultBrightness: 100,
    defaultContrast: 100,
    defaultSaturate: 100,
    defaultGrayscale: 0,
  });

  const handleSave = async () => {
    const editedFile = await generateEditedFile();
    // Do something with the edited file
  };

  return (
    <div>
      <canvas ref={canvasRef} />

      <div>
        <label>Brightness: {brightness}</label>
        <input
          type='range'
          min='0'
          max='200'
          value={brightness}
          onChange={(e) => setBrightness(Number(e.target.value))}
        />
      </div>

      {/* Add more controls for other parameters */}

      <button onClick={handleZoomIn}>Zoom In</button>
      <button onClick={handleZoomOut}>Zoom Out</button>
      <button onClick={resetFilters}>Reset</button>
      <button onClick={handleSave}>Save</button>
    </div>
  );
}

Hook Parameters

ParameterTypeDefaultDescription
fileFile | undefined-The image file to be edited
defaultBrightnessnumber100Initial brightness level
defaultContrastnumber100Initial contrast level
defaultSaturatenumber100Initial saturation level
defaultGrayscalenumber0Initial grayscale level
defaultFlipHorizontalbooleanfalseInitial horizontal flip state
defaultFlipVerticalbooleanfalseInitial vertical flip state
defaultZoomnumber1Initial zoom level
defaultRotatenumber0Initial rotation angle in degrees
defaultLineColorstring#000000Initial line color in hex code
defaultLineWidthnumber2Initial line/stroke width
defaultModestringpanInitial mode (draw or move)

Return Values

The hook returns the following values and functions:

🖼 Canvas & Image

NameTypeDescription
canvasRefRefObject<HTMLCanvasElement>Reference to the canvas element
imageSrcstringThe source of the loaded image

🎛 State Values & Setters

StateSetterTypeDescription
brightnesssetBrightnessnumberBrightness level (default 100)
contrastsetContrastnumberContrast level (default 100)
saturatesetSaturatenumberSaturation level (default 100)
grayscalesetGrayscalenumberGrayscale level (default 0)
rotatesetRotatenumberRotation angle in degrees
zoomsetZoomnumberZoom level
flipHorizontalsetFlipHorizontalbooleanFlip horizontally
flipVerticalsetFlipVerticalbooleanFlip vertically
modesetMode'draw' | 'move'Interaction mode (draw or move)
lineColorsetLineColorstringDrawing line color
lineWidthsetLineWidthnumberDrawing line width

🛠 Utility Functions

FunctionTypeDescription
handleZoomIn() => voidZoom in
handleZoomOut() => voidZoom out
resetFilters() => voidReset all filters and transformations
downloadImage() => voidDownload current canvas as an image
generateEditedFile() => Promise<File>Returns the edited canvas as a File object

🖱 Event Handlers

FunctionTypeDescription
handlePointerDownPointerEventHandlerUsed for drawing
handlePointerUpPointerEventHandlerUsed for drawing
handlePointerMovePointerEventHandlerUsed for drawing
handleWheelWheelEventHandlerUsed for zooming

🤝 Contributing

Contributions to react-photo-editor are welcome! If you have any issues, feature requests, or improvements, please open an issue or submit a pull request on the GitHub repository.

How to Contribute

  • Fork the repository
  • Create your feature branch: git checkout -b feature/amazing-feature
  • Commit your changes: git commit -m 'Add some amazing feature'
  • Push to the branch: git push origin feature/amazing-feature
  • Open a pull request

Reporting Issues

When reporting issues, please provide:

  • A clear description of the problem
  • Steps to reproduce
  • Expected vs actual behavior
  • Screenshots if applicable
  • Environment details (browser, OS, etc.)

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

FAQs

Package last updated on 05 Apr 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts