Effortless Image Handling in React with Cloudinary

The Challenge of Image Management

When building applications that rely on images, a seemingly simple task like uploading images to a server can become a daunting challenge. Fortunately, Cloudinary provides a solution to this problem, allowing us to upload and manage images directly from the frontend. In this article, we’ll explore how to handle images in React applications using Cloudinary.

Prerequisites

Before we dive in, make sure you have:

  • Basic knowledge of JavaScript and React
  • The latest version of Node.js installed on your machine
  • A terminal such as ITerm2 (Mac OS) or Git bash (Windows)
  • A Cloudinary account (create one if you don’t have one already)

Creating a Cloudinary Account

Cloudinary is a cloud-based image and video management platform used by developers and engineering teams to manage media assets. If you haven’t already, create a Cloudinary account, which we’ll use to store and retrieve our uploaded images.

Setting Up React

Let’s set up a small React application to demonstrate how to handle images in React with Cloudinary. Run the following command to create a new React app:


npx create-react-app my-app

Once the setup is complete, change the directory to your newly created React app and start it up:


cd my-app
npm start

Handling Images via Cloudinary Endpoint

To handle images via Cloudinary endpoint, we’ll upload images to Cloudinary by sending a POST request to a Cloudinary endpoint. This will upload the image and return a response object to us.

First, let’s write some JavaScript code to get the selected image from our device. Add the following block of code just before the return statement in the App function:


handleImageUpload = () => {
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
console.log(file);
}

This function queries the document to get the first input element with the type of file, then logs the first element of the array in the result to the console.

Next, we’ll send a POST request to a Cloudinary endpoint with the file object. Replace the handleImageUpload() function with the following code:


handleImageUpload = () => {
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', 'your_upload_preset');
const cloudName = 'your_cloud_name';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
fetch(url, {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));
}

Displaying the Uploaded Image

To display the uploaded image, replace the code that logs the result of the uploaded image to the console with the following code block:


handleImageUpload = () => {
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', 'your_upload_preset');
const cloudName = 'your_cloud_name';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
fetch(url, {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(result => {
const imageUrl = result.secure_url;
this.setState({ imageUrl });
})
.catch(error => console.error(error));
}

Handling Images via Cloudinary Widget

Another way to handle images is by using the Cloudinary widget, which allows us to upload images from various sources, such as Dropbox, Facebook, Instagram, and even take pictures with it.

First, include the widget’s remote JavaScript file in your index.html file located in public/index.html:

“`

“`

Next, create the widget and open it up when clicked. Add the following code above the render function:


createWidget = () => {
const cloudName = 'your_cloud_name';
const uploadPreset = 'your_upload_preset';
const widget = window.cloudinary.createUploadWidget({
cloudName,
uploadPreset,
multiple: false,
}, (error, result) => {
if (error) {
console.error(error);
} else {
const imageUrl = result.info.secure_url;
this.setState({ imageUrl });
}
});
widget.open();
}

Update your button with the class of widget-btn to call the createWidget() function when clicked:


<button className="widget-btn" onClick={this.createWidget}>Upload Image</button>

Now, when you click the widget button on your React app in the browser, you should see the Cloudinary widget, which allows you to upload images from various sources.

Conclusion

Cloudinary makes it easy to handle images in React applications, especially with the Cloudinary widget. The code for this project can be found in this repository for your reference.

Leave a Reply

Your email address will not be published. Required fields are marked *