### Install react-image-crop with Bun, npm, pnpm, or Yarn Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Use your preferred package manager to install the library. ```bash bun add react-image-crop ``` ```bash npm i react-image-crop --save ``` ```bash pnpm add react-image-crop ``` ```bash yarn add react-image-crop ``` -------------------------------- ### Import CSS Stylesheet Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/API-Index.md Import the pre-built CSS for basic styling. This is the simplest way to get started. ```typescript import 'react-image-crop/dist/ReactCrop.css' ``` -------------------------------- ### Complete Crop with Preview Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/api-reference/Browser-Crop-Addons.md A comprehensive example demonstrating how to use `ReactCrop` along with `cropToCanvas` and `cropToImg` to render a cropped image to a canvas and generate a preview URL. This setup allows for real-time previewing of the cropped area. ```typescript import React, { useState, useRef } from 'react' import ReactCrop, { cropToCanvas, cropToImg, type Crop, type PixelCrop, type PercentCrop, } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function CropWithPreview({ src }: { src: string }) { const imgRef = useRef(null) const previewCanvasRef = useRef(null) const [crop, setCrop] = useState({ unit: '%', x: 25, y: 25, width: 50, height: 50, }) const [completedCrop, setCompletedCrop] = useState(null) const [previewSrc, setPreviewSrc] = useState('') async function updatePreview(pixelCrop: PixelCrop) { if (!imgRef.current || !previewCanvasRef.current) { return } // Render to canvas await cropToCanvas(imgRef.current, previewCanvasRef.current, pixelCrop) // Generate preview URL const preview = await cropToImg(imgRef.current, pixelCrop) setPreviewSrc(preview) } return (
setCrop(percentCrop)} onComplete={(pixelCrop) => { setCompletedCrop(pixelCrop) void updatePreview(pixelCrop) }} aspect={16 / 9} > Crop source {completedCrop && (

Preview

{previewSrc && Crop preview}
)}
) } export default CropWithPreview ``` -------------------------------- ### Full-Featured Crop Editor Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Usage-Patterns.md This example showcases a comprehensive image cropping editor. It allows users to adjust aspect ratio, scale, and rotation, and provides a live preview. Ensure you have React, React Image Crop, and its CSS imported. ```typescript import React, { useState, useRef } from 'react' import ReactCrop, { centerCrop, makeAspectCrop, cropToCanvas, cropToImg, type Crop, type PixelCrop, type PercentCrop, } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function AdvancedCropEditor() { const imgRef = useRef(null) const canvasRef = useRef(null) const [crop, setCrop] = useState() const [completedCrop, setCompletedCrop] = useState(null) const [previewSrc, setPreviewSrc] = useState('') const [aspectRatio, setAspectRatio] = useState(1) const [scale, setScale] = useState(1) const [rotate, setRotate] = useState(0) function handleImageLoad(e: React.SyntheticEvent) { const { width, height } = e.currentTarget const newCrop = centerCrop( makeAspectCrop( { unit: '%', width: 90 }, aspectRatio || 1, width, height ), width, height ) setCrop(newCrop) } async function handleComplete(pixelCrop: PixelCrop) { setCompletedCrop(pixelCrop) if (imgRef.current && canvasRef.current) { await cropToCanvas(imgRef.current, canvasRef.current, pixelCrop, scale, rotate) const preview = await cropToImg(imgRef.current, pixelCrop, scale, rotate) setPreviewSrc(preview) } } return (
setCrop(c)} onComplete={handleComplete} aspect={aspectRatio} ruleOfThirds circularCrop={aspectRatio === 1} > Source {completedCrop && (

Preview

{previewSrc && Preview}
)}
) } export default AdvancedCropEditor ``` -------------------------------- ### Basic Crop Implementation with Minimal State Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Usage-Patterns.md A minimal example demonstrating how to set up react-image-crop with basic state management for the crop area. Requires React and react-image-crop imports. ```typescript import React, { useState } from 'react' import ReactCrop, { type Crop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function BasicCrop() { const [crop, setCrop] = useState() return ( setCrop(c)}> Crop me ) } ``` -------------------------------- ### Crop Implementation with State Tracking Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Usage-Patterns.md This example shows how to track crop state, including pixel and percentage values, and log them upon completion. It initializes the crop with specific pixel dimensions. ```typescript import React, { useState } from 'react' import ReactCrop, { type Crop, type PixelCrop, type PercentCrop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function CropWithTracking() { const [crop, setCrop] = useState({ unit: 'px', x: 0, y: 0, width: 200, height: 200, }) const [completedCrop, setCompletedCrop] = useState(null) return (
setCrop(c)} onComplete={(pixelCrop: PixelCrop, percentCrop: PercentCrop) => { setCompletedCrop(pixelCrop) console.log('Crop completed:', pixelCrop) }} > Crop me {completedCrop && (

Cropped area: {completedCrop.width}x{completedCrop.height}px

)}
) } ``` -------------------------------- ### Basic Crop Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/api-reference/ReactCrop.md Demonstrates the fundamental usage of React-Image-Crop. Import the component and CSS, then use it with an image source and manage the crop state. ```tsx import React, { useState } from 'react' import ReactCrop, { type Crop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function BasicCropExample({ src }: { src: string }) { const [crop, setCrop] = useState() return ( setCrop(c)}> Crop me ) } ``` -------------------------------- ### Crop Object Example (Percentage) Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Illustrates creating a Crop object with percentage units. This is useful for responsive designs where the crop scales with its container. ```typescript import { type Crop } from 'react-image-crop' const percentCrop: Crop = { x: 10, y: 10, width: 80, height: 80, unit: '%', } ``` -------------------------------- ### Basic React Crop Demo Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md A simple example demonstrating how to use ReactCrop with a functional component and state management for the crop. ```tsx import ReactCrop, { type Crop } from 'react-image-crop' function CropDemo({ src }) { const [crop, setCrop] = useState() return ( setCrop(c)}> ) } ``` -------------------------------- ### Crop Object Example (Pixels) Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Illustrates creating a Crop object with pixel units. This is commonly used for direct pixel-based positioning. ```typescript import { type Crop } from 'react-image-crop' const myCrop: Crop = { x: 50, y: 50, width: 200, height: 200, unit: 'px', } ``` -------------------------------- ### Basic Crop Setup Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/README.md Set up basic cropping functionality by managing the crop state and passing it to the ReactCrop component. This is used for interactive image cropping. ```typescript const [crop, setCrop] = useState() setCrop(c)}> ``` -------------------------------- ### Fixed Aspect Ratio and Limits Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/api-reference/ReactCrop.md Shows how to enforce a fixed aspect ratio and set minimum/maximum dimensions for the crop area. The `onComplete` prop is used to log the final crop details. ```tsx import React, { useState } from 'react' import ReactCrop, { type Crop, type PixelCrop, type PercentCrop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function FixedAspectExample({ src }: { src: string }) { const [crop, setCrop] = useState({ unit: 'px', x: 100, y: 100, width: 200, height: 200, }) const handleComplete = (pixelCrop: PixelCrop, percentCrop: PercentCrop) => { console.log('Crop completed:', pixelCrop) } return ( setCrop(c)} onComplete={handleComplete} aspect={1} minWidth={50} minHeight={50} maxWidth={400} maxHeight={400} > Crop me ) } ``` -------------------------------- ### PercentCrop Object Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Shows how to create a PercentCrop object, ensuring the unit is strictly '%'. This is useful for saving and restoring crop states across different image sizes or viewports. ```typescript import { type PercentCrop } from 'react-image-crop' const percentCrop: PercentCrop = { x: 25, y: 25, width: 50, height: 50, unit: '%', } // Save and restore across different image sizes: const saved = percentCrop // Save to database const restored = { ...saved } // Restore on different viewport ``` -------------------------------- ### Memoize Pixel Crop Conversion for Performance Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md This example shows how to use `useMemo` to optimize the conversion of crop coordinates to pixel values. Memoization prevents redundant calculations when the crop or container size hasn't changed, improving performance. ```typescript import React, { useMemo, useState } from 'react' import ReactCrop, { convertToPixelCrop, type Crop, type PixelCrop, } from 'react-image-crop' function MemoizedCropConversion() { const [crop, setCrop] = useState() const [containerSize, setContainerSize] = useState({ width: 800, height: 600 }) // Memoize pixel conversion const pixelCrop = useMemo(() => { if (!crop) return null return convertToPixelCrop(crop, containerSize.width, containerSize.height) }, [crop, containerSize]) return (
setCrop(c)}> Memoized crop {pixelCrop &&

Pixel crop: {pixelCrop.width}x{pixelCrop.height}

}
) } ``` -------------------------------- ### Count TypeScript Code Examples Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/MANIFEST.md Count the number of TypeScript code examples present in the markdown files by searching for fenced TypeScript code blocks. ```bash grep -c "```typescript" *.md ``` -------------------------------- ### Container-Based Responsive Crops Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Implement responsive image cropping that adapts to its container size. This example uses a ResizeObserver to track container dimensions and adjusts the crop accordingly. Ensure the image has `maxWidth: '100%'` and `height: 'auto'` for proper scaling. ```typescript import React, { useState, useRef, useEffect } from 'react' import ReactCrop, { makeAspectCrop, centerCrop, type Crop, type PercentCrop, } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function ResponsiveToContainer() { const containerRef = useRef(null) const [crop, setCrop] = useState() const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) useEffect(() => { function updateSize() { if (containerRef.current) { const { width, height } = containerRef.current.getBoundingClientRect() setContainerSize({ width, height }) } } updateSize() const observer = new ResizeObserver(updateSize) if (containerRef.current) { observer.observe(containerRef.current) } return () => observer.disconnect() }, []) function handleImageLoad(e: React.SyntheticEvent) { const { width, height } = e.currentTarget const newCrop = centerCrop( makeAspectCrop( { unit: '%', width: 90 }, 16 / 9, width, height ), width, height ) setCrop(newCrop) } return (
setCrop(c)} aspect={16 / 9}> Responsive crop

Container: {containerSize.width}x{containerSize.height}px

) } ``` -------------------------------- ### Initialize React Crop with No Selection Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Start with no crop selected by initializing the crop state to undefined. ```tsx const [crop, setCrop] = useState() setCrop(c)}> ``` -------------------------------- ### ReactCrop Component Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/README.md Documentation for the main ReactCrop component, including its props, static properties, keyboard events, CSS classes, and usage examples. ```APIDOC ## ReactCrop Component ### Description This is the main component of the react-image-crop library. It allows users to crop images within a React application. ### Props (Refer to `./api-reference/ReactCrop.md` for a complete list of props, including configuration options, styling, and event handlers.) ### Static Properties (Refer to `./api-reference/ReactCrop.md` for details on static properties.) ### Keyboard Events (Refer to `./api-reference/ReactCrop.md` for information on keyboard event handling.) ### CSS Classes (Refer to `./api-reference/ReactCrop.md` for a list of available CSS classes for styling.) ### Examples (Refer to `./api-reference/ReactCrop.md` for usage examples.) ``` -------------------------------- ### Initialize and Configure ReactCrop Component Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/configuration.md Example of a React component that initializes and configures the ReactCrop component. It manages crop state, handles image loading to set initial crop dimensions, and applies aspect ratio and size constraints. ```tsx import React, { useState, useRef } from 'react' import ReactCrop, { type Crop, type PixelCrop, centerCrop, makeAspectCrop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function ConfiguredCrop({ src }: { src: string }) { const [crop, setCrop] = useState({ unit: '%', x: 25, y: 25, width: 50, height: 50, }) const handleImageLoad = (e: React.SyntheticEvent) => { const { width, height } = e.currentTarget const newCrop = centerCrop( makeAspectCrop( { unit: '%', width: 90 }, 16 / 9, width, height ), width, height ) setCrop(newCrop) } return ( setCrop(c)} aspect={16 / 9} minWidth={50} minHeight={50} maxWidth={800} maxHeight={600} ruleOfThirds className="my-crop-container" ariaLabels={{ cropArea: 'Move crop area with arrow keys', }} > Crop source ) } export default ConfiguredCrop ``` -------------------------------- ### Example Usage of ReactCropState in renderSelectionAddon Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Demonstrates how to access and use the ReactCropState within the renderSelectionAddon prop to conditionally render UI elements based on user interaction. ```typescript import { type ReactCropState } from 'react-image-crop' renderSelectionAddon={(state: ReactCropState) => (
{state.cropIsActive && Adjusting crop...} {state.newCropIsBeingDrawn && Drawing new crop...}
)} ``` -------------------------------- ### PixelCrop Object Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Demonstrates the creation of a PixelCrop object, ensuring the unit is strictly 'px'. This type is required by functions like `cropToCanvas`. ```typescript import { type PixelCrop } from 'react-image-crop' const pixelCrop: PixelCrop = { x: 100, y: 100, width: 300, height: 300, unit: 'px', } // TypeScript ensures unit is 'px': // const invalid: PixelCrop = { x: 0, y: 0, width: 100, height: 100, unit: '%' } // ^^^ Type error: unit must be 'px' ``` -------------------------------- ### Example: Custom Styling with Inline Styles and CSS Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/configuration.md Apply custom styles to the React Image Crop component by using the `className` and `style` props, and by defining custom CSS rules in a separate stylesheet. ```tsx import ReactCrop, { type Crop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' import './custom-crop-styles.css' function CustomStyledCrop() { const [crop, setCrop] = useState() return ( Crop me ) } ``` ```css .custom-crop-wrapper .ReactCrop__crop-selection { border: 3px solid #ff5722; } .custom-crop-wrapper .ReactCrop__drag-handle { background-color: #ff5722; width: 12px; height: 12px; border-radius: 50%; } ``` -------------------------------- ### Custom Render with Rule of Thirds Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/api-reference/ReactCrop.md Illustrates custom rendering within the crop selection, including enabling the 'rule of thirds' overlay and displaying custom content when the crop is active. The `aspect` prop is set to a 16:9 ratio. ```tsx import React, { useState } from 'react' import ReactCrop, { type Crop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function CustomRenderExample({ src }: { src: string }) { const [crop, setCrop] = useState({ unit: '%', x: 25, y: 25, width: 50, height: 50, }) return ( setCrop(c)} aspect={16 / 9} ruleOfThirds renderSelectionAddon={({ cropIsActive }) => (
{cropIsActive && Dragging...}
)} > Crop me
) } ``` -------------------------------- ### Crop with Transform Example Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/api-reference/Browser-Crop-Addons.md Demonstrates how to use react-image-crop to crop an image and apply transformations such as scaling and rotation. This component allows users to adjust these parameters interactively and render the final cropped and transformed image to a canvas. ```typescript import React, { useState, useRef } from 'react' import ReactCrop, { cropToCanvas, type Crop, type PixelCrop, } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function CropWithTransform({ src }: { src: string }) { const imgRef = useRef(null) const canvasRef = useRef(null) const [crop, setCrop] = useState({ unit: 'px', x: 100, y: 100, width: 300, height: 300, }) const [scale, setScale] = useState(1) const [rotate, setRotate] = useState(0) async function handleRender() { if (imgRef.current && canvasRef.current) { const pixelCrop = crop as PixelCrop await cropToCanvas(imgRef.current, canvasRef.current, pixelCrop, scale, rotate) } } return (
setCrop(c)}> Crop me
) } export default CropWithTransform ``` -------------------------------- ### Implement Keyboard Event Handling for Cropping Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Integrate custom keyboard event handling to control crop adjustments. This example shows how to modify the crop's position based on arrow key presses, with different step sizes for Shift and Ctrl keys. ```typescript import React, { useState, useRef } from 'react' import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop' function KeyboardControlledCrop() { const [crop, setCrop] = useState({ unit: 'px', x: 100, y: 100, width: 200, height: 200, }) const componentRef = useRef(null) function handleDocumentKeyDown(e: KeyboardEvent) { const step = e.shiftKey ? 10 : e.ctrlKey ? 100 : 1 if (e.key === 'ArrowUp' && crop) { e.preventDefault() setCrop({ ...crop, y: Math.max(0, crop.y - step) }) } else if (e.key === 'ArrowDown' && crop) { e.preventDefault() setCrop({ ...crop, y: crop.y + step }) } } return (
setCrop(c)}> Keyboard controlled
) } ``` -------------------------------- ### Generate Crop Preview with Canvas and Image Object URL Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Use `cropToCanvas` to render a crop to a canvas or `cropToImg` to get an image object URL. Both helpers accept optional `scale` and `rotate` arguments. ```tsx import { useRef, useState } from 'react' import ReactCrop, { cropToCanvas, cropToImg, type Crop, type PixelCrop } from 'react-image-crop' function CropPreview({ src }: { src: string }) { const imgRef = useRef(null) const previewCanvasRef = useRef(null) const [crop, setCrop] = useState() const [completedCrop, setCompletedCrop] = useState() const [previewSrc, setPreviewSrc] = useState('') async function updatePreview(crop: PixelCrop) { if (!imgRef.current || !previewCanvasRef.current) { return } await cropToCanvas(imgRef.current, previewCanvasRef.current, crop) setPreviewSrc(await cropToImg(imgRef.current, crop)) } return ( <> setCrop(percentCrop)} onComplete={c => { setCompletedCrop(c) void updatePreview(c) }} > Crop me {!!completedCrop && } {!!previewSrc && Crop preview} ) } ``` ```ts await cropToCanvas(image, canvas, completedCrop, scale, rotate) const previewSrc = await cropToImg(image, completedCrop, scale, rotate) ``` -------------------------------- ### View Entry Point File Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/MANIFEST.md Use this command to view the main entry point file of the project. ```bash cat 00-START-HERE.md ``` -------------------------------- ### File Structure Overview Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/DOCUMENTATION-INDEX.md This snippet outlines the directory structure of the react-image-crop project, indicating the purpose of each documentation file. ```text output/ ├── README.md # Documentation overview and quick navigation ├── DOCUMENTATION-INDEX.md # This file ├── API-Index.md # Quick lookup of all symbols ├── types.md # All type definitions ├── configuration.md # Props, config, and build setup ├── Usage-Patterns.md # Code examples for common scenarios ├── Advanced-Topics.md # Deep dives and integration patterns └── api-reference/ ├── ReactCrop.md # Main component reference ├── Crop-Utilities.md # Utility function reference └── Browser-Crop-Addons.md # Canvas/image output reference ``` -------------------------------- ### High DPI Canvas Export Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Demonstrates how `cropToCanvas` automatically utilizes `devicePixelRatio` for sharper canvas output on high-DPI displays. The example logs the canvas dimensions and exports the result as a PNG. ```typescript import React, { useRef } from 'react' import { cropToCanvas, type PixelCrop } from 'react-image-crop' async function HighDPIExport(crop: PixelCrop) { const canvas = document.createElement('canvas') const image = document.querySelector('img') as HTMLImageElement // cropToCanvas applies devicePixelRatio automatically await cropToCanvas(image, canvas, crop) // Canvas dimensions are larger on high-DPI displays console.log( `Canvas: ${canvas.width}x${canvas.height}px`, `Display: ${Math.round(canvas.width / window.devicePixelRatio)}x${Math.round(canvas.height / window.devicePixelRatio)}px` ) // Export as PNG return canvas.toDataURL('image/png', 0.95) } ``` -------------------------------- ### Import Custom Crop Logic Utilities Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/API-Index.md Import utilities for programmatic manipulation of crop data, including conversion between pixel and percentage units, nudging, bounds validation, and equality checks. ```typescript import { convertToPixelCrop, convertToPercentCrop, nudgeCrop, containCrop, areCropsEqual, } from 'react-image-crop' ``` -------------------------------- ### View Specific API File Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/MANIFEST.md Use this command to view the content of a specific API reference file, such as ReactCrop.md. ```bash cat api-reference/ReactCrop.md ``` -------------------------------- ### Handle Resize Based on Ordinate Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md Example demonstrating how to use the 'Ords' type to handle different resize operations based on the ordinate value. This is useful for differentiating between edge and corner resizing. ```typescript import { type Ords } from 'react-image-crop' function handleResize(ord: Ords) { if (ord === 'nw' || ord === 'ne' || ord === 'n') { // User is resizing from the top console.log('Top edge resize') } if (ord === 'se') { // User is resizing from bottom-right corner console.log('Corner resize') } } ``` -------------------------------- ### Get Handle Position from Ords Type Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/types.md The `Ords` type represents the eight possible positions of a crop handle. This function maps an `Ords` value to a descriptive string for UI positioning. ```typescript import { type Ords } from 'react-image-crop' function getHandlePosition(ord: Ords): string { const positions: Record = { n: 'top-center', s: 'bottom-center', e: 'right-center', w: 'left-center', nw: 'top-left', ne: 'top-right', se: 'bottom-right', sw: 'bottom-left', } return positions[ord] } ``` -------------------------------- ### Common React Image Crop Import Patterns Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/DOCUMENTATION-INDEX.md Demonstrates various ways to import React Crop components and utilities. Choose the import that best suits your needs, whether it's the full component, specific utilities, or type definitions. ```typescript // Minimal import ReactCrop from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' ``` ```typescript // With types import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop' ``` ```typescript // Utilities only import { makeAspectCrop, centerCrop, cropToCanvas, cropToImg } from 'react-image-crop' ``` ```typescript // Specific functions import { convertToPixelCrop, convertToPercentCrop } from 'react-image-crop' ``` -------------------------------- ### Generate Preview Image with cropToImg Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/00-START-HERE.md Shows how to use the `cropToImg` utility function to generate a preview image URL from an image element and crop data. This function is asynchronous and requires an image element and pixel crop data. ```typescript const previewUrl = await cropToImg(imageElement, pixelCrop) ``` -------------------------------- ### React Image Crop Import Reference Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/README.md Shows how to import the main component, types, and utility functions from the react-image-crop library, along with its CSS. ```typescript // Main component import ReactCrop from 'react-image-crop' ``` ```typescript // With types import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop' ``` ```typescript // Specific utilities import { makeAspectCrop, centerCrop, cropToCanvas } from 'react-image-crop' ``` ```css // Styles import 'react-image-crop/dist/ReactCrop.css' ``` -------------------------------- ### Crop Image for Form Submission Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Integrate image cropping directly into a form submission process. This example shows how to generate a cropped image preview and include its data as a hidden input field for form submission. ```typescript import React, { useState, useRef } from 'react' import ReactCrop, { cropToImg, type Crop, type PixelCrop, } from 'react-image-crop' function CropFormField() { const imgRef = useRef(null) const [crop, setCrop] = useState() const [croppedSrc, setCroppedSrc] = useState('') async function handleComplete(pixelCrop: PixelCrop) { if (imgRef.current) { const url = await cropToImg(imgRef.current, pixelCrop) setCroppedSrc(url) } } return (
{ e.preventDefault() // Form submission with cropped image console.log('Submitting crop:', croppedSrc) }} > setCrop(c)} onComplete={handleComplete} > Crop {croppedSrc && (

Preview:

Cropped preview
)}
) } ``` -------------------------------- ### Initialize React Crop with Preselected Crop Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Set an initial crop selection by providing a predefined crop object to the crop state. ```tsx const [crop, setCrop] = useState({ unit: '%', x: 25, y: 25, width: 50, height: 50 }) setCrop(c)}> ``` -------------------------------- ### Crop SVG Elements with React Crop Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Apply cropping to an SVG element using React Crop. This example sets up a circular SVG and demonstrates how to define crop parameters for it, including a fixed aspect ratio. ```typescript import React, { useState } from 'react' import ReactCrop, { type Crop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function SVGCrop() { const [crop, setCrop] = useState({ unit: 'px', x: 0, y: 0, width: 200, height: 200, }) return ( setCrop(c)} aspect={1}> {/* SVG content */} ) } ``` -------------------------------- ### List All Markdown Sections Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/MANIFEST.md This command lists all top-level sections (H1 headings) in all markdown files within the project. ```bash grep "^# " *.md ``` -------------------------------- ### Configure Centered Crop with Percentage Units Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Use percentage units for `unit`, `width`, `height`, `x`, and `y` to easily center a crop. For aspect ratio crops, use `makeAspectCrop` and `centerCrop` helper functions. ```js crop: { unit: '%', width: 50, height: 50, x: 25, y: 25 } ``` ```jsx ``` ```js function onImageLoad(e) { const { naturalWidth: width, naturalHeight: height } = e.currentTarget const crop = centerCrop( makeAspectCrop( { // You don't need to pass a complete crop into // makeAspectCrop or centerCrop. unit: '%', width: 90, }, 16 / 9, width, height ), width, height ) setCrop(crop) } ``` ```js const onCropChange = (crop, percentCrop) => setCrop(percentCrop) ``` -------------------------------- ### Custom Crop Validation with React Image Crop Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Implement custom validation logic to enforce minimum and maximum dimensions for the crop area. This example shows how to check width and height and display validation errors to the user. ```typescript import React, { useState } from 'react' import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop' function ValidatedCrop() { const [crop, setCrop] = useState({ unit: 'px', x: 0, y: 0, width: 200, height: 200, }) const [validationError, setValidationError] = useState('') function handleChange(c: Crop) { // Validate crop const pixelCrop = c as PixelCrop const errors: string[] = [] if (pixelCrop.width < 50) { errors.push('Crop width must be at least 50px') } if (pixelCrop.height < 50) { errors.push('Crop height must be at least 50px') } if (pixelCrop.width > 800) { errors.push('Crop width cannot exceed 800px') } setValidationError(errors.join('; ')) setCrop(c) } return (
Validated crop {validationError &&

{validationError}

}
) } ``` -------------------------------- ### Import React-Image-Crop CSS Source: https://github.com/dominictobias/react-image-crop/blob/master/README.md Include the necessary CSS for styling. You can use either the CSS or SCSS version. ```javascript import 'react-image-crop/dist/ReactCrop.css' ``` ```javascript // or scss: import 'react-image-crop/src/ReactCrop.scss' ``` -------------------------------- ### Cleanup Blob URLs in React Image Crop Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md This example demonstrates how to manage and clean up Blob URLs generated by cropToImg to prevent memory leaks. It includes manual cleanup within the function and automatic cleanup on component unmount. ```typescript import React, { useEffect, useRef } from 'react' import { cropToImg, type PixelCrop } from 'react-image-crop' function CleanupExample() { const blobUrlsRef = useRef([]) async function generateCropWithCleanup( image: HTMLImageElement, crop: PixelCrop ) { // cropToImg internally revokes previous URL const newUrl = await cropToImg(image, crop) blobUrlsRef.current.push(newUrl) // Manual cleanup if needed return () => { blobUrlsRef.current.forEach((url) => URL.revokeObjectURL(url)) blobUrlsRef.current = [] } } useEffect(() => { return () => { // Cleanup on unmount blobUrlsRef.current.forEach((url) => URL.revokeObjectURL(url)) } }, []) return
{/* Component content */}
} ``` -------------------------------- ### Import React Crop with CommonJS Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/configuration.md Import ReactCrop and its types using CommonJS. Remember to require the CSS file for proper styling. ```javascript const ReactCrop = require('react-image-crop').default const { type Crop } = require('react-image-crop') require('react-image-crop/dist/ReactCrop.css') ``` -------------------------------- ### Responsive Crop with Percentage Units Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Usage-Patterns.md Implement responsive cropping by using percentage units for crop dimensions. This ensures the crop scales correctly across different screen sizes. The `handleCropChange` function updates the state with percentage-based crop values. ```typescript import React, { useState } from 'react' import ReactCrop, { type Crop, type PercentCrop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' function ResponsiveCrop() { // Use percentage crop to be resolution-independent const [crop, setCrop] = useState({ unit: '%', x: 10, y: 10, width: 80, height: 80, }) function handleCropChange(c: Crop, percentCrop: PercentCrop) { setCrop(percentCrop) // Store as percentage for responsiveness } return ( Responsive crop ) } ``` -------------------------------- ### Crop Conversion Utilities Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/API-Index.md Utilities for converting crop objects between different units (pixels and percentages) based on container dimensions. ```APIDOC ## convertToPixelCrop ### Description Convert any crop to pixels based on container size. ### Signature `(crop: Partial, containerWidth: number, containerHeight: number) => PixelCrop` ### Source `src/utils.ts` ### Returns `PixelCrop` ``` ```APIDOC ## convertToPercentCrop ### Description Convert any crop to percentages based on container size. ### Signature `(crop: Partial, containerWidth: number, containerHeight: number) => PercentCrop` ### Source `src/utils.ts` ### Returns `PercentCrop` ``` -------------------------------- ### Import React Crop with ES Modules Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/configuration.md Recommended method for importing ReactCrop and its types using ES Modules. Ensure you also import the CSS for styling. ```typescript import ReactCrop, { type Crop, centerCrop, makeAspectCrop } from 'react-image-crop' import 'react-image-crop/dist/ReactCrop.css' ``` -------------------------------- ### Import Preview Generation Utilities Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/API-Index.md Import functions for converting crop data into canvas elements or image URLs, and the PixelCrop type. Useful for post-crop processing. ```typescript import { cropToCanvas, cropToImg, type PixelCrop } from 'react-image-crop' ``` -------------------------------- ### Manage Pixel and Percent Crops Simultaneously Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/Advanced-Topics.md Use percentage crops for responsive UI and pixel crops for canvas operations. The `convertToPixelCrop` and `convertToPercentCrop` utilities help manage conversions. ```typescript import React, { useState } from 'react' import ReactCrop, { convertToPixelCrop, convertToPercentCrop, type Crop, type PixelCrop, type PercentCrop, } from 'react-image-crop' function DualCropTracking() { // Store percentage for responsiveness, use pixels for canvas operations const [percentCrop, setPercentCrop] = useState(null) function handleChange(pixelCrop: PixelCrop, percentCrop: PercentCrop) { // Save percentage for persistence setPercentCrop(percentCrop) // Pixels are available immediately for canvas ops console.log('Current pixel crop:', pixelCrop) } // When restoring a saved crop from different image size function restoreCrop(container: HTMLDivElement, savedPercentCrop: PercentCrop) { const { width, height } = container.getBoundingClientRect() const restoredPixelCrop = convertToPixelCrop(savedPercentCrop, width, height) // Use restoredPixelCrop } return ( Crop me ) } ``` -------------------------------- ### Core API Usage of ReactCrop Component Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/00-START-HERE.md Demonstrates the basic integration of the ReactCrop component, including setting crop properties and handling changes. Ensure the `ReactCrop` component and its associated types are imported. ```typescript setCrop(percentCrop)} aspect={16/9} > Crop me ``` -------------------------------- ### Import Aspect-Locked Crop Utilities Source: https://github.com/dominictobias/react-image-crop/blob/master/_autodocs/API-Index.md Import utilities for creating aspect-ratio-locked crops and centering them. Use these in addition to the basic crop UI imports. ```typescript import { makeAspectCrop, centerCrop } from 'react-image-crop' ```