Search code examples
reactjscropcropperjs

Unable to create instance to Cropperjs using react-cropper


I studied the documentation on Github and tried to apply it.

The problem is - I am unable to initialize the cropper instance. As per the documentation we have to use onInitialized method. I did that, but I am unable to fire it.

When should I assume it should be fired - When a component is mounted or when I add image to it? Documentation is super blurry. Below is my code. It seems like onCropperInit function was never fired.

import React from 'react';
import Cropper from 'react-cropper';

export default class Demo extends React.Component{
    
    constructor(){
        super();
        this.state={
            image: "#"
        }
        this._crop = this._crop.bind(this);
        this.onCropperInit = this.onCropperInit.bind(this);
        this.onChange = this.onChange.bind(this)
    }
    
    
 onChange(e) {
     
        e.preventDefault();
        let files;
    
            files = e.target.files;
        const reader = new FileReader();
  
        reader.onload = () => {
            this.setState({
            image: reader.result
            })
        };
        reader.readAsDataURL(files[0]);
    };
    _crop(){
  
    }


onCropperInit(cropper){
console.log("cropper")
    this.cropper = cropper;
}

render(){
    return (
        <div>
         <input type="file" onChange={this.onChange} />
    
        <Cropper src={this.state.image} style={{height:"100vh",width: "90vw"}} aspectRatio={1067/600} guides={true} crop={this._crop} onInitialized={this.onCropperInit} dragMode="move"/>
    </div>
            )
}
}

Solution

  • You're right. The github documentation says to use onInitialized, but it doesn't seem to work.

    At least for now you can use a ref to get the cropper instance like this:

    const cropper = React.createRef(null);
    
    class Demo extends React.Component {
      constructor(props) {
        super(props);
        this._crop.bind(this);
      }
    
      _crop() {
        console.warn(cropper.current.cropper.getCroppedCanvas());
      }
    
      render() {
        return (
          <Cropper
            src="http://fengyuanchen.github.io/cropper/images/picture.jpg"
            style={{ height: 400, width: '100%' }}
            initialAspectRatio={16 / 9}
            guides={false}
            crop={this._crop}
            ref={cropper}
          />
        );
      }
    }