Quickstart Guide to using Cloudinary Upload Widget v2 in React
After doing more research, I found that Cloudinary had just released a new version (v2) of their upload widget the previous month (October 2018). The new version of the widget was made to take advantage of new technologies such as React, ES6, WebPack, and Rollup.js with an updated design and improved mobile support. Since I was using React and tried to build a PWA, I thought using this widget was a great option.
However, I ran into an obstacle where the cloudinary object was being returned as undefined everywhere in my src directory and there did not seem to be any helpful information online about how to implement the Cloudinary Upload Widget v2 in a react app. Cloudinary’s own widget documentation did not have the answer to why I was having difficulty accessing the cloudinary object, which I needed to create the widget. This is why I decided to write a blog post about it so that other developers wouldn’t waste as much time as I did getting the widget to work. Below is a breakdown of how I set it up in the end.
1.Sign up for a free Cloudinary account, then go to Settings, click the Upload tab, and scroll to the bottom to click the button to create a new unsigned upload preset. You will need that upload preset name and your cloud name, which can be found on your Cloudinary dashboard, for later.
4. Create a callback function for showing the widget. Adding the widget above creates the object in memory but does not show the widget on the page. You need to call .open on the widget to show it on the screen and .close to remove from the screen.
5. Add a function inside the callback function of the .createUploadWidget method that checks the result response give from the widget to get the secure URL for the uploaded image. When an image is uploaded, the result object will have an event key with a “success” value, and the object will also have an info object with a secure_url key whose value is the URL to the uploaded photo.
Note: there is also a .openUploadWidget method that both creates and opens the widget. However, separating the two methods helps with performance by allowing your widget to load right away in the background.
For more in-depth information on how to take advantage of all upload widget features see the Cloudinary documentation.