Skip to content Skip to sidebar Skip to footer

How To Implement Cloudinary Upload Widget In React?

I'm trying to use the Cloudinary Upload Widget in my React App but i have a problem. When running the project, the Upload Widget appears immediately, but when closed and opened aga

Solution 1:

First, let's understand the issue. The Cloudinary upload widget is defined in the render function of the component and when that component is rendered, it will open the upload widget since it's defined with the functionality of openUploadWidget. Secondly, the widget is defined only in the scope of the render function and not accessible outside of it, hence the error widget.open() is not a function.

To remedy these issues, I would first start by defining the widget either as a local variable or part of the state. This is done by including the constructor as part of your component:

constructor(props) {
   super(props)

   // Defined in statethis.state = { . . . }

   // Defined as local variablethis.widget = myLocalVariable
}

The next thing to do is when creating an instance of the Cloudinary upload widget, to use createUploadWidget and not openUploadWidget, to allow control of when to open the widget.

constructor(props) {
   super(props)
   // Defined in statethis.state = {
      widget: cloudinary.createUploadWidget({
         cloudName: 'my_cloud_name', 
         uploadPreset: 'my_preset'}, 
         (error, result) => { 
            if (!error && result && result.event === "success") { 
               console.log('Done! Here is the image info: ', result.info); 
            }
         }
      })
    }
    // Defined as local variablethis.widget = cloudinary.createUploadWidget({
       cloudName: 'my_cloud_name', 
       uploadPreset: 'my_preset'}, (error, result) => { 
         if (!error && result && result.event === "success") { 
           console.log('Done! Here is the image info: ', result.info); 
         }
       }
    })
 }

Lastly, the showWidget click event does not need the widget passed as an argument (since it's defined locally in the component) and can be referred too with the this keyword. Note that you'll need to include the keyword this to refer to the current component.

showWidget = () => {
  this.widget.open();
}

I have included a JSFiddle showing the end result: https://jsfiddle.net/danielmendoza/fve1kL53/

Solution 2:

I will add that you might need to rewrite the showWidget function to prevent the event default if you're trying to set the state with the URL result. Otherwise, you'll get an error that you cannot use setState() in an unmounted component.

showWidget = (e) => {
  e.preventDefault();
  this.widget.open();
}

Post a Comment for "How To Implement Cloudinary Upload Widget In React?"