Add An Image Cropper To Your React App
We recently published the CropGuide browser module, this module makes it easier to integrate CropGuide with web applications. In this quick tutorial we’ll use the module to add image cropping to a React app.
Creating A Basic React App
We’ll start by setting up a new React using create-react-app
npx create-react-app my-app
Now that we’ve got a basic app set up, we can install CropGuide.
Installing The CropGuide Browser Module
Let’s navigate to our my-app
folder and then we’ll run the following command to install the CropGuide module.
npm i @cropguide/browser --save
The CropGuide module is a tiny module that helps load and configure the CropGuide image cropper script.
Initialising The CropGuide Module
Let’s open the src/App.js
file and import the CropGuide module.
import logo from './logo.svg';
import './App.css';
/* Import the CropGuide module */
import CropGuide from '@cropguide/browser';
/* Load the script and pass your client key as the first argument */
CropGuide('ABC123');
The CropGuide
function returns a Promise
so we can easily handle errors and know when CropGuide is ready.
CropGuide('ABC123')
.resolve(() => {
console.log('CropGuide has initialised');
})
.catch((err) => {
console.error(err);
});
Debuggin And Custom Field Configuration
The CropGuide
function accepts a second configuration argument, we can use it to pass custom field configurations and to enable debug mode.
CropGuide('ABC123', {
// Enable debug mode
debug: true,
});
Here we set the fields
property to limit CropGuide to the element with id 'profile-picture'
This means CropGuide will handle file input elements or file drop events that happen to the element or one of the elements in its subtree.
CropGuide('ABC123', {
// Enable debug mode
debug: true,
fields: ['#profile-picture'],
});
Conclusion
We’ve learned we can use the CropGuide browser module to quickly load CropGuide in web application environments.
Using the debug
property we can show the CropGuide loading process, by setting the fields
property we can configure how CropGuide interacts with the fields in our app.