When building an application, best practices call for reducing the noise around the image to direct the user’s attention to a specific part of the image. Image cropping is a method of processing an image to remove any unwanted elements. By changing the aspect ratio or orientation, we can draw the viewer’s eye to the subject of the photo and improve the overall composition.

In this article, we will compare the three top React image clipping libraries, React Avatar Editor, React – Cropper, and React – Easy-Crop, evaluating each library in terms of performance, popularity, and developer experience.

First, we’ll build an image uploader application in React that we’ll use in each library. By the end of this tutorial, you should be able to choose the right person for your project. To follow this tutorial, you will need.

  • React and JavaScript basics
  • Install Node.js and NPM on your machine

Let’s get started!

You can learn this by accessing the project code.

Initialize a new React application with the Create React App

We first initialize a new React App with the Create React App and boot it; Run the following command on your terminal to create a new React application.

npx create-react-app image uploader

Copy the code

Next, we’ll navigate to our project directory and run the following command to start our development server.

cd image uploader && yarn start 

Copy the code

The command above opens a TAB in our browser that displays the default template for the application. Next, we’ll install the dependencies, which we’ll include in our three Cropper libraries.

dependencies

We will install the following dependencies in our application.

  • react-cropper:cropperjsAct as the React component.
  • React Image Crop: a zero-dependent cropping tool for React images.
  • React – Avatar-editor: a lightweight clipping tool with no dependencies.
  • React-easy-crop: A React component that can easily crop images.
  • Styled – Components: A component used to write CSS in our JavaScript.
  • Tailwind CSS: Utility classes for tailoring components.

Next, we will create components for our component. In our application, we will need a Button component to upload images, and a Modals component that will upload, save, and delete images from our uploader. Finally, we will need a modalWrapper for each of our clippers.

Buttoncomponent

The Button component is the skeleton of all the buttons in our application.

First, we’ll use the style component to create a style guide for our buttons. First, let’s create a Components folder in our application’s SRC directory. In your Components folder, create a new directory called Button; In this folder, create a button.jsx file and add the following code.

import styled from "styled-components"; const Button = ({ children, className, ... props }) => { return ( <StyledButton style={{ background: "skyblue", color: "# 000", }} className={`${className} block text-black px-6 rounded-md font-semibold hover:opacity-75 transition-opacity duration-500 ease-in`} type="button" {... props} > {children} </StyledButton> ); };Copy the code

In the code block above, we create a Button component and pass children, className, and props. Now, we will style our buttons using styled- Components.

const StyledButton = styled.button`
    background-color: #2eff7b;
    border: none;
    outline: none;
    height: 45px;
    &:focus {
        border: none;
        outline: none;
    }
    &:disabled {
        opacity: 1;
        cursor: not-allowed;
    }
`;
export default Button;

Copy the code

Checkboxcomponent

Now we will create a Checkbox component that links each image clipper. First, create a new folder called Checkbox in our component directory. Inside, we’ll create a new file called checkbox.jsx and add the following code.

import styled from "styled-components"; const Checkbox = ({ label, onChange, id, isChecked }) => { return ( <Wrapper> <label htmlFor={id}>{label}</label> <input id={id} type="checkbox" name={label} onChange={() => { onChange(! isChecked ? label : null); }} value={isChecked ? label : ""} checked={isChecked} /> <span className="rounded-full" /> </Wrapper> ); };Copy the code

In the code block above, we create a Checkbox component with a label and an ID that we will use to select our clipper library. Next, we will create a Modal component that opens and closes a particular clipping library.

Create ourmodalcomponent

Our modal component will have items like onModalClose, showModal, and onSaveHandler. We will also add a button for uploading and saving our cropped images.

In our Components directory, let’s create a new folder called Modal. Inside, create a new file named modal.jsx and add the following code block.

import { createPortal } from "react-dom"; import styled from "styled-components"; import Button from ".. /Button/Button"; const Modal = ({ children, onModalClose, showModal, onSaveHandler }) => { return createPortal( <Wrapper style={{ opacity: showModal ? 1 : 0, pointerEvents: showModal ? "all" : "none", }} > <div onClick={onModalClose} role="button" className="iu-modal-backdrop" style={{ display: showModal ? "flex" : "none", }} /> <div className="iu-modal-content"> {children} <footer className="px-12 md:sticky absolute bottom-0 bg-white w-full  left-0 py-4 border-t border-black flex items-center justify-between"> <Button onClick={onModalClose}>Dismiss</Button> <Button onClick={() => { onSaveHandler(); onModalClose(); }} > Save </Button> </footer> </div> </Wrapper>, document.getElementById("modal") ); };Copy the code

In the code block above, we initialize a Modal component and create a Wrapper component, where we add a function to upload and save images.

react-avatar-editor

React – Avatar-editor is an avatar and image clipper for react applications. With an intuitive user interface, react-Avatar-Editor makes it easy to crop, resize, and rotate images.

With 85,000 downloads per week on NPM and 18,000 stars on GitHub, the React – Avatar-Editor is one of the most popular clipper libraries in the React app. To see the React – Avatar-editor in action, first we need to install it in our application with the following command.

//Yarn 

yarn add react-avatar-editor

//npm

npm install --save react-avatar-editor

Copy the code

Next, create a new folder called ReactAvatarEditor. Inside, create a new file called ReactAvatarEditor. JSX and add the following code.

import { useRef } from "react";
import AvatarEditor from "react-avatar-editor";
import styled from "styled-components";
import Modal from "../../Modal/Modal";

const ReactAvatarEditor = ({
    showModal,
    onModalClose,
    imgURL,
    onSaveHandler,
}) => {
    const EditorRef = useRef(null);
    const showCroppedImage = async () =&gt; {
        if (EditorRef.current) {
            const img = EditorRef.current.getImage().toDataURL();
            return img;
        }
    };

    return (
        <Modal
            showModal={showModal}
            onSaveHandler={async () => onSaveHandler(await showCroppedImage())}
            onModalClose={onModalClose}
        >
            <Wrapper className="w-full h-full flex flex-col items-center justify-center">
                <AvatarEditor
                    ref={EditorRef}
                    image={imgURL}
                    width={250}
                    height={250}
                    border={0}
                    scale={1.2}
                    color={[255, 255, 255, 0.6]}
                />
            </Wrapper>
        </Modal>
    );
};

Copy the code

In the code above, we import the useRef Hook, initialize our Cropper Packager as AvatarEditor, and import styled- Components to add styling to our application.

We then initialize a functional component with AvatarEditor and pass some methods from our Modal component. Finally, we assign ref to our AvatarEditor to get our image, convert it to a URL, and parse it for clipping.

To render the image we cropped, we create a wrapper component and add items such as image, which is the URL of the image we cropped. Note that the width, height, border, color attribute refers to the editor.

react-cropper

React-cropper is an open source react wrapper for Cropper.js, a JavaScript library that includes a photo editor and image clipper. React-cropper has over 63K weekly downloads on NPM and 1.6K stars on GitHub. To use react-Cropper in your application, first, install it with the following command.

// Using yarn 
yarn add react-cropper 

// Using npm
npm install --save react-cropper 

Copy the code

Next, add the following code block to crop the image using our image uploader application.

import { useRef, useState } from "react"; import Cropper from "react-cropper"; import "cropperjs/dist/cropper.css"; import Modal from ".. /.. /Modal/Modal"; const ReactCropper = ({ showModal, onModalClose, imgURL, onSaveHandler }) => { const cropperRef = useRef(null); const [croppedImg, setCroppedImg] = useState(""); const onCrop = () => { const imageElement = cropperRef? .current; const cropper = imageElement? .cropper; setCroppedImg(cropper.getCroppedCanvas().toDataURL()); }; return ( <Modal showModal={showModal} onSaveHandler={() => onSaveHandler(croppedImg)} onModalClose={onModalClose} > <Cropper src={imgURL} style={{ height: 500, width: "732px" }} initialAspectRatio={16 / 9} guides={false} crop={onCrop} ref={cropperRef} viewMode={1} // guides={true} minCropBoxHeight={10} minCropBoxWidth={10} // background={false} responsive={true} autoCropArea={1} aspectRatio={4 / 3} checkOrientation={false} /> </Modal> ); }; export default ReactCropper;Copy the code

Like react- Avatar-Editor, we import useRef and useState Hooks from React. Next, we initialize a feature component, ReactCropper, which receives items such as image URLS and Modal.

To crop our image, we connect to the image clipper’s properties, such as the image URL, and parse it. Using React’s useState Hook, we create a state for our cropped image.

To render our image, we initialize a Cropper component and pass some props from cropper.js, including SRC to parse the image URL. Finally, we pass the style to the Style item.

react-easy-crop

React – Easy-Crop is an open source React component that has a neat UI for cropping images and videos. React-easy-crop is mobile-friendly, offering cropped dimensions in pixels and percentages, as well as drag and zoom interactions.

On NPM, React-Easy-Crop is currently being downloaded more than 125,000 times a week. On GitHub, React-Easy-Crop has 14,000 stars. You can get started using React-easy-Crop by installing the library using the package manager, as shown in the code block below.

//Yarn 
yarn add react-easy-crop

// npm
npm install react-easy-crop --save

Copy the code

To use React-easy-Crop, you need to wrap it in a Cropper component tag. Let’s use the following library to build a clipper component.

import { useCallback, useState } from "react"; import Cropper from "react-easy-crop"; import Modal from ".. /.. /Modal/Modal"; const ReactEasyCrop = ({ showModal, onModalClose, imgURL, onSaveHandler }) => { const [crop, setCrop] = useState({ x: 2, y: 2 }); const [zoom, setZoom] = useState(1); const [croppedArea, setCroppedArea] = useState(""); const onCropComplete = useCallback((croppedArea, croppedAreaPixels) => { setCroppedArea(croppedAreaPixels); } []); const showCroppedImage = useCallback(async () => { try { const croppedImage = await getCroppedImg(imgURL, croppedArea, 0); return croppedImage; } catch (error) { console.error(error); } }, [croppedArea, imgURL]);Copy the code

In the code block above, we created a component called ReactEasyCrop that contains items like showModal, onModalClose, imgURL, onSaveHandler, and showModal.

Like other image clippers, showModal and onModalClose props are used to upload images, while imgUrl provides the URL of the image we want to upload.

OnCropComplete allows us to save the cropped area of the image and specify the pixel or percentage size of the cropped image. Next, we will render our application using the Modal wrapper component, as shown in the figure below.

return (
                <Modal
                        showModal={showModal}
                        onSaveHandler={async () => onSaveHandler(await showCroppedImage())}
                        onModalClose={onModalClose}
                >
                        <div className="relative w-full">
                                <Cropper
                                        image={imgURL}
                                        crop={crop}
                                        zoom={zoom}
                                        aspect={4 / 3}
                                        onCropChange={setCrop}
                                        onCropComplete={onCropComplete}
                                        onZoomChange={setZoom}
                                />
                        </div>
                </Modal>
        );
};

export default ReactEazyCrop;

Copy the code

In the code block above, we wrapped the entire application in a Modal component that enabled us to upload our images. Next, we initialize the Cropper component, where we pass in the URL of our cropped image.

We also added crop to determine the position of the image to crop. Zoom, used to zoom in on images, is set to 1 by default.

OnCropChange is used to update the clipping state of our application. OnCropComplete is called when the user stops zooming the image.

conclusion

No matter what type of project you’re working on, the clipper library can help you improve your overall user interface by removing unwanted areas from your photos. The libraries described in this tutorial have full built-in functionality and are easy to customize.

You should now be able to choose the right clipper library for your application. I hope you enjoyed this tutorial