Skip to content

Commit

Permalink
feat: provide widget api with react refs (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeetiss committed Aug 28, 2019
1 parent d7b23b6 commit 311b6e4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 20 deletions.
41 changes: 23 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useLayoutEffect } from 'react'
import React, { useLayoutEffect, forwardRef } from 'react'
import { lazy, Suspense } from '@uploadcare/client-suspense'

const Uploader = lazy(() =>
Expand Down Expand Up @@ -28,24 +28,29 @@ const Config = ({ locale, localeTranslations, localePluralize }) => {
return null
}

export const Widget = ({
locale,
localeTranslations,
localePluralize,
preloader = 'Loading...',
...props
}) => (
<>
<Config
locale={locale}
localeTranslations={localeTranslations}
localePluralize={localeTranslations}
/>
export const Widget = forwardRef(
(
{
locale,
localeTranslations,
localePluralize,
preloader = 'Loading...',
...props
},
ref
) => (
<>
<Config
locale={locale}
localeTranslations={localeTranslations}
localePluralize={localeTranslations}
/>

<Suspense fallback={preloader}>
<Uploader {...props} />
</Suspense>
</>
<Suspense fallback={preloader}>
<Uploader {...props} apiRef={ref} />
</Suspense>
</>
)
)

export const Panel = ({
Expand Down
30 changes: 28 additions & 2 deletions src/uploader.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import React, { useEffect, useRef, useMemo, useCallback } from 'react'
import React, {
useEffect,
useRef,
useMemo,
useCallback,
useImperativeHandle
} from 'react'
import uploadcare from 'uploadcare-widget'

import {
Expand Down Expand Up @@ -26,14 +32,24 @@ const useWidget = (props, uploadcare) => {
value,
onFileSelect,
onChange,
apiRef,
customTabs,
validators,
options
] = useDestructuring(
({ value, onFileSelect, onChange, customTabs, validators, ...options }) => [
({
value,
onFileSelect,
onChange,
apiRef,
customTabs,
validators,
...options
}) => [
value,
onFileSelect,
onChange,
apiRef,
customTabs,
validators,
options
Expand Down Expand Up @@ -104,6 +120,16 @@ const useWidget = (props, uploadcare) => {
widget.current.value(value)
}, [value])

useImperativeHandle(
apiRef,
() => ({
openDialog: () => widget.current.openDialog(),
reloadInfo: () => widget.current.reloadInfo(),
getInput: () => widget.current.inputElement
}),
[]
)

return useCallback(
() => <input type='hidden' ref={input} {...attributes} />,
[attributes]
Expand Down

0 comments on commit 311b6e4

Please sign in to comment.