Preview with progress for file uploading in React

Yoav Niran
2 min readMay 22, 2020

A few weeks ago I posted about a new library called react-uploadyModern file-upload components & hooks for React.

The previous post was an introduction to the library and a little taste of how simple it is to get file-upload to work in your app. If you haven’t read it, I recommend taking a look first before continuing reading.

In this post I’d like to demonstrate how easy it is, with RU, to show a preview of an image being uploaded while spicing it up a little by animating the opacity of the preview to indicate the progress of the upload.

That’sa Spice Meatball

Let’s jump straight into the code.

The full example is available in the following sandbox:

For this demo we’ll be using three packages from react-uploady:

  1. @rpldy/uploady — the uploady wrapper and context provider
  2. @rpldy/upload-button — a ready-made upload button
  3. @rpldy/upload-preview — a ready-made previewer for uploads

Now we just need a little wiring up and a little CSS and we’re good to go.

For this demo, this will be our App wrapper. Notice the use of <Uploady> which has to wrap the inner components and hooks. They won’t work unless they’re rendered under an Uploady instance.

Inside our App and inside Uploady we render our new component called: UploadWithProgressPreview.

This component renders an <UploadButton> and an <UploadPreview> which will show a preview for the file being uploaded. An image for an image file, a video for a video file, and can accept a fallback for other types (not shown here). It also accepts a custom preview component that we define in the next code sample.

Notice the getPreviewProps, it allows us to pass additional info to the preview component. In this case we pass the item id so we can use it in our custom preview.

Our CustomImagePreview uses the useItemProgressListener hook to receive the upload progress percentage for the uploading item. Since a batch may include multiple items, it uses the id from the preview props to compare with the progress event’s item.

The percentage value is passed to the styled <img> tag that sets the opacity based on this. This way the image fades in as it’s upload progresses until completion.

The end result looks like this:

Try react-uploady today! 😃

--

--

Yoav Niran

I write. Code by day, science fiction by night. Check out my first novel at: https://whitecloudsbook.com