The Cloudinary ecosystem offers a vast array of features and advanced capabilities for managing your media content. However, to harness this power effectively, you must begin by uploading your images and videos to Cloudinary. While you could manually accomplish this task using Cloudinary’s extensive APIs and SDKs, there’s a more streamlined way to go about it.
In this Dev Hint, we’ll delve into the world of Cloudinary and explore how to integrate the Upload Widget into an empty React application. We’ll guide you through the steps of effortlessly dropping this widget right into the heart of your web page, making media uploads a breeze. Let’s get started!
To get started, the first step is to load the script into our React application. You can access the widget code directly from the Cloudinary Upload Widget documentation.
Copy the script from the documentation and include it in your index.html file, found in the public folder of your React project directory. Paste the script at the bottom of the <head>
section as shown below:
<!-- Place this script at the bottom of the <head> section in your 'index.html' file -->
<script src="https://upload-widget.cloudinary.com/global/all.js" type="text/javascript">
</script>
Code language: HTML, XML (xml)
If a more suitable script loading solution already exists in your application, feel free to use that method.
With this, our widget script will load synchronously whenever the application loads.
To maintain a clean code base, it’s advisable not to include all the code inside the primary app file. Instead, we’ll create a separate component for this purpose. Let’s call it “UploadWidget.js”.
In the UploadWidget.js file, define and export a new component called UploadWidget. Once this is done, we’ll need a way to store references of the loaded code, whenever our Upload script runs. React’s useRef
and useEffect
hooks come in handy here.
Here’s a brief snippet showing how to do this:
import { useEffect, useRef } from 'react';
const UploadWidget = () => {
const cloudinaryRef = useRef();
useEffect(() => {
cloudinaryRef.current = window.cloudinary;
}, []);
};
export default UploadWidget;
Code language: JavaScript (javascript)
After creating the component and setting up the required references, it’s time to utilize the UploadWidget component by exporting it to the App.js file, as demonstrated below:
import UploadWidget from './components/UploadWidget';
import './App.css';
function App() {
return (
<main className="main">
<div className="container">
<h1 className="title">
React & Cloudinary Upload Widget
</h1>
<UploadWidget />
</div>
</main>
);
}
export default App;
Code language: JavaScript (javascript)
Let’s now focus on creating the upload widget and preparing it for uploads. We’ll pass onto it two arguments: our configuration and a result function that’ll handle the result of the uploads. The configuration is a simple JavaScript object containing two key-value pairs: the “cloud name” and the “upload preset”.
You can find the cloud name easily under the account details on your dashboard under your Account Details section as highlighted below.
Since we’ll be performing an unsigned upload, we’ll require an unsigned upload preset. To create an upload preset, follow these steps:
- Access the Cloudinary Settings section.
- Navigate to the Upload tab.
- Scroll down to locate the Upload Presets section.
- Click Add Upload Preset.
- In the Upload Preset Name field, modify the name or use the default one.
- Set the Signing Mode to Unsigned.
- Adjust any other settings as necessary for your upload preset.
- Once you’re satisfied with the configuration, click Save.
After configuring all the necessary settings, the next step involves initializing the Cloudinary Upload Widget when the component is mounted.
This can be achieved by adding the following to the useEffect
hook we defined above in the UploadWidget.js file :
useEffect(() => {
cloudinaryRef.current = window.cloudinary;
widgetRef.current = cloudinaryRef.current.createUploadWidget({
cloudName: 'Your_cloudName',
uploadPreset: 'Your_uploadPreset'
}, function(error, result) {
console.log(result);
// Handle the result or error here
});
}, []);
Code language: JavaScript (javascript)
In the useEffect
above, we set up the Cloudinary Upload Widget using the createUploadWidget function. This widget is configured with your Cloudinary account details and an upload preset. When users interact with the widget, a callback function logs the upload result, such as the file’s URL, to the console. This code is the foundation for integrating Cloudinary’s file upload feature into a web application.
The next step is to create a reference (widgetRef
) using the useRef
hook that will be used by the upload button to trigger the opening of the Cloudinary Upload Widget. This useRef
reference will allow us to control and interact with the widget when the button is clicked. This can be achieved by the following code:
const widgetRef = useRef();
Code language: JavaScript (javascript)
To finalize the component, return a straightforward JSX structure containing a single button. The button has an onClick
listener, which, when clicked, will trigger the opening of the Cloudinary Upload Widget using widgetRef.current.open()
method, as shown below:
return (
<div>
<button onClick={() => widgetRef.current.open()}>
Upload
</button>
</div>
);
Code language: JavaScript (javascript)
With all of these steps and code in place, the UploadWidget
component will display a button labeled “Upload”. When a user clicks this button, it will trigger the Cloudinary Upload Widget to open. This will allow users to select and upload files (such as images or videos) to your Cloudinary account. The uploaded files will be processed according to the specified upload preset and stored in your Cloudinary media library. If the upload is successful, the component will log information about the uploaded file(s) to the console. Any potential errors during the upload process can also be handled as needed.
The Cloudinary Upload Widget significantly improves the ease of uploading images and videos to our media library. Easy to integrate and rich in features, the widget is an inherent piece of a React application that promises to smooth out the upload process.
Deploying this widget is a fine balance between functionality and utility, and remains true to React’s convention of maintaining neat, readable code. You’ll find that your users will admire the effortless interaction that this widget enables.
Happy coding!
If you found this article helpful and want to discuss it in more detail, head over to Cloudinary Community forum and its associated Discord.