Adjust image size with react - personalize styling for react-easy-crop

I am currently working on developing a basic react component that involves cropping images using react-easy-crop. It seems like the style of the react-easy-crop module can be customized with the style prop, which consists of three objects: containerStyle, mediaStyle, and cropAreaStyle.

Here is the default layout:

https://i.sstatic.net/yjPv9.png

I am aiming to expand the cropArea to cover the full width of its container and adjust the media to fit in by height, eliminating any parts of the original image visible outside the cropArea. However, I am having trouble achieving this as it appears that the cropAreaStyle object does not affect width or height due to being calculated and injected in the module file (even after setting disableAutomaticStylesInjection to true).

import React from 'react'
import ReactDOM from 'react-dom'
import Cropper from 'react-easy-crop'
import './styles.css'

class App extends React.Component {
  state = {
    imageSrc:
      'https://img.huffingtonpost.com/asset/5ab4d4ac2000007d06eb2c56.jpeg?cache=sih0jwle4e&ops=1910_1000',
    crop: { x: 0, y: 0 },
    zoom: 1,
    aspect: 1 / 1,
    style: {  containerStyle: { position: "absolute", top: "0", width: "calc(100% - 2px)", height: window.innerWidth, overflow: "hidden", border: "1px solid black" }, 
              mediaStyle: { height: "100%", display: "block" }, 
              cropAreaStyle: {position: "absolute", top: "0", border: "1px solid black", width: "100%", height: "100%" }}
  }

  onCropChange = (crop) => {
    this.setState({ crop })
  }

  onCropComplete = (croppedArea, croppedAreaPixels) => {
    console.log(croppedArea, croppedAreaPixels)
  }

  onZoomChange = (zoom) => {
    this.setState({ zoom })
  }

  render() {
    return (
      <div className="App">
        <div className="crop-container">
          <Cropper
            image={this.state.imageSrc}
            crop={this.state.crop}
            zoom={this.state.zoom}
            aspect={this.state.aspect}
            onCropChange={this.onCropChange}
            onCropComplete={this.onCropComplete}
            onZoomChange={this.onZoomChange}
            style={this.state.style}
            disableAutomaticStylesInjection={true}
          />
        </div>
      </div>
    )
  }
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

This is my desired outcome:

https://i.sstatic.net/diZYH.png

The black square represents the cropArea that I am struggling to resize...

I want to maintain the cropArea as a square.

Is there a simple way to achieve this without modifying the module file?

Alternatively, I am open to suggestions involving a different module.

Thank you in advance

Answer №1

Instead of using the object cropAreaStyle which is not working, try using the prop cropSize and avoid passing the prop aspect.

To obtain the height of the media, make sure to pass the prop onMediaLoaded:

onMediaLoad = (mediaSize) => {
    this.setState({
      cropHeight: mediaSize.height,
    });
  };

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import Cropper from 'react-easy-crop';
import './style.css';

class App extends React.Component {
  state = {
    imageSrc:
      'https://img.huffingtonpost.com/asset/5ab4d4ac2000007d06eb2c56.jpeg?cache=sih0jwle4e&ops=1910_1000',
    crop: { x: 0, y: 0 },
    zoom: 1,
    cropHeight: 0,
  };

  onCropChange = (crop) => {
    this.setState({ crop });
  };

  onCropComplete = (croppedArea, croppedAreaPixels) => {
    console.log(croppedArea, croppedAreaPixels);
  };

  onZoomChange = (zoom) => {
    this.setState({ zoom });
  };

  onMediaLoad = (mediaSize) => {
    this.setState({
      cropHeight: mediaSize.height,
    });
  };

  render() {
    const cropSize = {
      height: `${this.state.cropHeight}px`,
      width: '100%',
    };

    return (
      <div className="App">
        <div className="crop-container">
          <Cropper
            image={this.state.imageSrc}
            crop={this.state.crop}
            zoom={this.state.zoom}
            onCropChange={this.onCropChange}
            onCropComplete={this.onCropComplete}
            onZoomChange={this.onZoomChange}
            onMediaLoaded={this.onMediaLoad}
            cropSize={cropSize}
          />
        </div>
      </div>
    );
  }
}

export default App;

Demo: https://stackblitz.com/edit/react-4zmgud

Answer №3

We apologize for any inconvenience, but you could try adjusting the position relative to the cropper's parent element and then specify the width and height of the parent element that the cropper will utilize

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to implement a feature in my notes application built with the MERN stack using Mongoose for MongoDB that allows users to add hidden notes. How

I am looking to implement a hidden notes functionality in my web application. When the "hide note" button is clicked, I want the note to be removed from its current location and added to a hidden notes section. Users should then have the ability to view an ...

What are the consequences of incorporating getInitialProps within _document.js that leads to a crash in the Next.js application?

What are the implications of using getInitialProps in _document.js for static rendering? How can it potentially impact the overall static rendering process? Consider the following scenarios: A small e-commerce website with a mix of static and dynamic pa ...

Navigate to a different tab using react router by adding history.push with a new link

After executing some logic, I want to open a link in a new tab. This is the button I have: <Button onClick={handleSubmit} > Preview </Button> The handleSubmit() function looks like this: const history = useHistory(); const handleSubmit = ...

What are some methods for customizing the calendar icon displayed in an input field with type date?

Is there a way to customize the calendar logo without relying on jquery? The desired appearance should resemble the image shown below: https://i.sstatic.net/G06iZ.png input { width: 50%; padding: 8px; border-radius: 10px; ...

The error detected in the W3Schools validator pertains to CSS for audio elements that do not contain

Could somebody kindly explain why this code is being flagged as an error on w3schools? audio:not([controls]) { display: none; height: 0; } ...

The color of the text on the Homepage appears differently on iOS Safari

At the top of my homepage, I have displayed the company phone number with white text color. It appears correctly as white on my desktop browsers (Firefox and Chrome), also on my Droid phone, but shows up as dark gray on my iOS phone using Safari. Why is th ...

Populate div with straight lines running vertically or horizontally

I'm wondering how to create vertical or horizontal lines inside a div. I tried this in the past but lost the code, and searching for "fill div with lines" isn't giving me any relevant results. Here's an image to illustrate what I'm try ...

"Error handling in React AJAX post requests is not triggering the success or error methods as expected

Within my React Component, there is an AJAX POST request that successfully creates a new entry in the database (status 201 returned). However, I am facing an issue where the success and error methods are not being triggered. $.ajax({ url: &apo ...

"Step-by-Step Guide to Dividing and Centering Text Sections with Dynamic

Initially, my intention is to implement the concept outlined below. The webpage has dual potential states. In the first scenario, two texts (with potentially varying lengths) are centralized together as a header. When transitioning to the second state, the ...

React component fails to update upon state change via Redux

I've noticed that my state is changing in the console, but my Book component isn't being refreshed when the state changes. In my app, I have two containers/components: BookList, which renders a list of all available books, and the Book component, ...

Displaying left and right div elements alongside each other in HTML/CSS works in Chrome, but not in Safari or Firefox

I've encountered an issue with aligning divs side by side in Firefox and Safari, although it seems to be working perfectly in Chrome. It's a bit tricky to provide all the CSS code as I have different stylesheets for mobile, normal, and print vers ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Retrieve and showcase information, subject to a certain criteria

I have developed an "API" that returns a group of users, and then I present these users in a table. The data returned by the code consists of two variables as shown in this image: "isActive" and "isVerified", both having values of either "false" or "true" ...

When a React component mounts repeatedly, it can lead to complications within the useEffect hook

In our React application, we have implemented a custom hook to send data to Google Analytics. To avoid sending duplicate values, we included a unique "marker" string that captures the value of the data being sent. The hook generates a new "marker" each tim ...

Failed Attempt to Execute React Native Application using Command Prompt (iOS)

I'm currently working through the React Native tutorial found on their official website. During my project building process, I utilized the following command: react-native run-ios An error was encountered: Found Xcode project TestProject.xcodeproj ...

In ReactJS, the behavior of event.currentTarget differs from that of Vanilla Javascript

Is there an equivalent of event.currentTarget in ReactJS? When using event.target on click, I am getting the childDiv instead of the desired parentDiv. For example, in Vanilla Javascript: document.getElementById("parentDiv").onclick = function() { ...

Determine the difference between a CSS selector string and an XPath string

Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector) function that can handle both css selectors and XPath selectors in string form. My dilemma lies in determining whether a given ...

Unsupported MIME format

I'm encountering an issue where my stylesheet is not applying to my handlebars. It was working fine yesterday, but today I'm seeing a MIME error and I'm unsure of the reason behind it. Any assistance would be greatly appreciated. Server Cod ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Unable to choose an input form within a CSS div

Just installed a jQuery responsive menu tab but encountering issues with selecting forms to input values. It seems like a CSS problem that I cannot identify. Please assist me in resolving this issue. Below is the HTML code snippet: <div class="contai ...