Skip to content

uploadcare/react-widget

Repository files navigation

React Wrapper for jQuery File Uploader

⚠️ Notice: File Uploader Option

This uploading wrapper remains fully functional and can be a great fit for your projects, especially if you have specific needs for jQuery. However, we recommend exploring our new React File Uploader to access the latest features and improvements.


This React component helps you integrate Uploadcare jQuery File Uploader into your React app natively; props management and lazy loading are bundled.

The component allows users to upload files from any file system and device, social media, cloud storage, and more. Best-in-class for image upload. All that without any backend code that’s usually required to handle uploads.

Build Status NPM version

Install

npm i @uploadcare/react-widget

Usage

import { Widget } from "@uploadcare/react-widget";

<Widget publicKey="YOUR_PUBLIC_KEY" />;

or

import { Panel } from "@uploadcare/react-widget";

<Panel publicKey="YOUR_PUBLIC_KEY" />;

To use this component, get an API key from your Uploadcare project.

Uploadcare account provides services for file uploads, transformations, CDN delivery, as well as APIs. After signing up, you'll see Dashboard where you can manage projects. Each Project is identified by its public key. Replace YOUR_PUBLIC_KEY with your project’s Public API Key and you are all set.

You can refer to our integration guide for more details.

Available bundles

By default, npm and other package managers import the full (all locales) CommonJS or ESM bundle.

To reduce your bundle size, you can also import one of the following:

  • The english-only bundle (saves ~27% in bundle size) as @uploadcare/react-widget/en
  • The minified all-locales bundle (saves ~44% in bundle size) as @uploadcare/react-widget/min
  • The minified english-only bundle (saves ~60% in bundle size) as @uploadcare/react-widget/en-min

Configuration

Widget component configuration

value: string[] | string | JQuery.Deferred | JQuery.Deferred[]

Set an array of file UUID/group UUID/CDN URL/File Instance/Group Instance as a value.

<Widget value='9dd2f080-cc52-442d-aa06-1d9eec7f40d1' />
<Widget value='9dd2f080-cc52-442d-aa06-1d9eec7f40d1~12' />
<Widget value={[
  '9dd2f080-cc52-442d-aa06-1d9eec7f40d1',
  'https://ucarecdn.com/fdfe4e67-f747-4993-91f5-be21d6d3c1a6/',
  '9ef9af26-7356-4428-b69c-1b920f947989~2'
]} />

onChange: (fileInfo: FileInfo) => void

Set a function to be called after a file is uploaded and ready.


onFileSelect: (fileInfo: FileInfo | FilesInfo | null) => void

Set a function to be called after a new file is selected.


onDialogOpen: (dialog: DialogApi) => void

Set a function to be called after dialog is opened.


onDialogClose: (objs: FileInfo | FilesInfo | null) => void

Set a function to be called after dialog is closed.


onTabChange: (tabName: string) => void

Set a function to be called after tab is changed.


metadata: (metadata: Record<string, string>)

The option can be used to set metadata object associated with the uploaded file.

Note that metadata supports string values only, any non-string value will be converted to string, including boolean, number, null and undefined.

WARNING: If this option is specified, option metadataCallback will be overridden (without merging). This is opposite from the uploadcare-widget's behavior.

See Metadata docs for details.


metadataCallback: () => Record<string, string>

Defines the function that specifies the actual metadata object a file uploader should use to associate with the uploaded file. It's helpful in the case of dynamic metadata object.

Note that metadata supports string values only, any non-string value will be converted to string, including boolean, number, null and undefined.

See Metadata docs for details.


customTabs: {[key: string]: CustomTabConstructor}

Add custom tabs for a widget.

function myTab(container, button, dialogApi, settings, name, uploadcare) {
  ...
}

<Widget customTabs={{ tabname: myTab }} />

Since custom tabs are global internally, any local property change will affect all the widget instances. So we're highly recommend not to redefine tab constructors and not to have different constructors under the same name.

Note that we added the fifth argument to the custom tab constructor — an uploadcare object. The widget is lazily-loaded, so you don’t have to import uploadcare-widget separately for your custom tab.

Remember that you also need to include your custom tab in the tabs prop to make it work:

<Widget customTabs={{ tabname: myTab }} tabs='tabname' />

  1. Install uploadcare-widget-tab-effects package
npm i uploadcare-widget-tab-effects
  1. Import one of the bundles:
  • uploadcare-widget-tab-effects/react for all-locales bundle
  • uploadcare-widget-tab-effects/react-en for english-only bundle
import effects from 'uploadcare-widget-tab-effects/react'
// or
// import effects from 'uploadcare-widget-tab-effects/react-en'
  1. Pass the effects object to the customTabs prop:
<Widget previewStep customTabs={{ preview: effects }} />

validators: Validator[]

Set validators for a widget. Validator is a JavaScript function that receives a fileInfo object for each uploaded file and throws an exception if that file doesn't meet validation requirements.

const fileTypeLimit = (allowedFileTypes: string) => {
  const types = allowedFileTypes.split(' ')

  return function(fileInfo: FileInfo) {
    if (fileInfo.name === null) {
      return
    }
    const extension = fileInfo.name.split('.').pop()

    if (extension && !types.includes(extension)) {
      throw new Error('fileType')
    }
  }
}

const validators = [fileTypeLimit('mp3 avi mp4')];

<Widget validators={validators} />

preloader: ComponentType

Set a custom preloader. A preloader component shows up when the widget is being loaded.


ref: widgetApiRef

Define a reference object to address the Widget API wrapper. Use it to access these methods: value, openDialog, reloadInfo and getInput.

  1. value() is the alias for widget.value()
  2. openDialog() is the alias for widget.openDialog()
  3. reloadIngo() is the alias for widget.reloadInfo()
  4. getInput() returns widget's input element instance.

Example:

const Example = () => {
 const widgetApi = useRef();
 return (
   <>
     <button onClick={() => widgetApi.current.openDialog()}>
       Click me
     </button>
     <Widget ref={widgetApi} publicKey=“demopublickey” />
   </>
 );
};

tabsCss: string

Optional. Define a custom CSS for tabs opened in iframes (e.g., Facebook, Instagram, etc.). It can be a CSS string or an absolute URL to a CSS file.

// Via URL
<Widget tabs="facebook" tabsCss="https://site.com/styles/uc.tabs.css"/>

// Via plain CSS
<Widget tabs="facebook" tabsCss=".source-facebook { background: #1877F2; }"/>

Note that all iframe tabs are opened via HTTPS, so linked CSS files should also be available over HTTPS.


Panel component configuration

value: string[] | string | JQuery.Deferred | JQuery.Deferred[]

Set an array of file UUID/group UUID/CDN URL/File Instance/Group Instance as a value.

<Panel value={[
  '9dd2f080-cc52-442d-aa06-1d9eec7f40d1',
  'https://ucarecdn.com/fdfe4e67-f747-4993-91f5-be21d6d3c1a6/',
  '9ef9af26-7356-4428-b69c-1b920f947989~2'
]} />

onChange: (fileInstanceList: FileInstance[]) => void

Set a function to be called whenever files state changes.


onProgress: (uploadInfoList: UploadInfo[]) => void

Set a function to be called whenever progress state changes.


ref: panelApiRef

Define a reference object to address the Dialog API wrapper.

Dialog API reference

interface DialogApi {
  addFiles(type: string, files: any[]): void;
  addFiles(files: Array<JQuery.Deferred<FileInfo>>): void;
  switchTab(tab: string): void;
  getFileColl(): CollectionOfPromises<FileInfo>;
  hideTab(tab: string): void;
  showTab(tab: string): void;
  isTabVisible(tab: string): boolean;
  onTabVisibility(callback: OnTabVisibilityCallback): void;
}

Those methods works exactly the same way as in Widget component:

Those methods aren't supported in Panel component:

Widget configuration

jQuery File Uploader can be deeply customized to suit your UX/UI. You can define allowed upload sources, implement file validation, and more.

All the options defined in the widget options docs are also supported in the component as props (use the camelCase notation, you can find it under “Object key” in the referenced article).

Use the live jQuery File Uploader as a starting point and consider checking out the docs on widget configuration.

Security issues

If you ran into something in Uploadcare libraries that might have security implications, please hit us up at [email protected] or Hackerone.

We’ll contact you shortly to fix and issue prior to any public disclosure.

Feedback

We want to hear your issue reports and feature requests at [email protected].