Search code examples
reactjsreact-hooksformikuploadcare

React UploadCare Remove Button Should Return Null


I wanted to make the value of imageUrl to be null if the remove button is click using uploadcare/react-widget. Right now, it doesn't set the value to null, it still returns the value of the original imageUrl. How do you call the function when you click the 'remove button'?

                    <Widget
                      tabs="file"
                      name="imageUrl"
                      clearable="true"
                      imagesOnly="true"
                      previewStep="true"
                      value={props.values.imageUrl}
                      onChange={upload =>
                        props.setFieldValue('imageUrl', upload.originalUrl)
                      }
                      publicKey={process.env.UPLOADCARE_KEY}
                    />

Solution

  • The onChange callback fires only when a file is uploaded. If you need to handle this case, consider using onFileSelect instead. For example,

    const Example = () => {
      return (
        <Widget
          publicKey={process.env.UPLOADCARE_KEY}
          previewStep
          clearable
          onFileSelect={file => {
            if (!file) {
              console.log("File removed from widget");
              return;
            }
            file.done(fileInfo => {
              console.log("File uploaded: ", fileInfo.cdnUrl);
            });
          }}
        />
      );
    };
    

    Make sure to update react-widget to the latest version (1.3.7) to be able to use this method.

    Basically, onFileSelect is a binding to the onChange method of the vanilla JS API of the widget.