Giter VIP home page Giter VIP logo

react-activestorage-provider's Introduction

react-activestorage-provider

NPM

ActiveStorage is an amazing addition to Rails 5.2, and as usual the team have made it fantastically simple to use... if you’re generating HTML server-side, that is. This component aims to make it just as easy to use from React.

ActiveStorageProvider handles the direct upload of a file to an ActiveStorage service and the attachment of that file to your model. It uses the render props pattern so you can build your own upload widget.

Install

npm install --save react-activestorage-provider

Usage

ActiveStorageProvider makes it easy to add a simple upload button. When you call handleUpload with a FileList or an array of Files, this component creates a Blob record, uploads the file directly to your storage service, and then hits your Rails controller to attach the blob to your model. (If you want to handle the attachment yourself, see below.)

<ActiveStorageProvider
  endpoint={{
    path: '/profile',
    model: 'User',
    attribute: 'avatar',
    method: 'PUT',
  }}
  onSubmit={user => this.setState({ avatar: user.avatar })}
  render={({ handleUpload, uploads, ready }) => (
    <div>
      <input
        type="file"
        disabled={!ready}
        onChange={e => handleUpload(e.currentTarget.files)}
      />

      {uploads.map(upload => {
        switch (upload.state) {
          case 'waiting':
            return <p key={upload.id}>Waiting to upload {upload.file.name}</p>
          case 'uploading':
            return (
              <p key={upload.id}>
                Uploading {upload.file.name}: {upload.progress}%
              </p>
            )
          case 'error':
            return (
              <p key={upload.id}>
                Error uploading {upload.file.name}: {upload.error}
              </p>
            )
          case 'finished':
            return <p key={upload.id}>Finished uploading {upload.file.name}</p>
        }
      })}
    </div>
  )}
/>

ActiveStorageProvider Props

These are your options for configuring ActiveStorageProvider.

Prop (*required) Description
endpoint* { path: string, model: string, attribute: string, method: string, host?: string, port?: string, protocol?: string }
The details for the request to attach the file
multiple boolean
Whether the component should accept multiple files. If true, the model should use has_many_attached
onBeforeBlobRequest ({ id: string, file: File, xhr: XMLHttpRequest }) => mixed
A callback that allows you to modify the blob request
onBeforeStorageRequest ({ id: string, file: File, xhr: XMLHttpRequest }) => mixed
A callback that allows you to modify the storage request
onError Response => mixed
A callback to handle an error (>= 400) response by the server in saving your model
onSubmit* Object => mixed
A callback for the server response to successfully saving your model
render* RenderProps => React.Node
Render props
token string
Optional authorization token

RenderProps

This is the type of the argument with which your render function will be called.

export type RenderProps = {
  ready: boolean /* false while any file is uploading */,
  uploads: ActiveStorageFileUpload[] /* uploads in progress */,

  handleUpload: (FileList | File[]) => mixed /* call to initiate an upload */,

  /* or, if you want more granular control... */

  /* call to set list of files to be uploaded */
  handleChooseFiles: (FileList | File[]) => mixed,
  /* then call to begin the upload of the files in the list */
  handleBeginUpload: () => mixed,
}

type ActiveStorageFileUpload =
  | { state: 'waiting', id: string, file: File }
  | { state: 'uploading', id: string, file: File, progress: number }
  | { state: 'error', id: string, file: File, error: string }
  | { state: 'finished', id: string, file: File }

DirectUploadProvider

ActiveStorageProvider makes it simple to add a quick “upload” button by taking care of both uploading and attaching your file, but it shouldn’t stand in your way if you’re doing something more interesting. If you want to handle the second step, attaching your Blob record to your model, yourself, you can use the lower level DirectUploadProvider. It creates the blob records and uploads the user’s files directly to your storage service, then calls you back with the signed ids of those blobs.

Prop (*required) Description
directUploadsPath string
The direct uploads path on your Rails app, if you’ve overridden ActiveStorage::DirectUploadsController
multiple boolean
Whether the component should accept multiple files. If true, the model should use has_many_attached
onBeforeBlobRequest ({ id: string, file: File, xhr: XMLHttpRequest }) => mixed
A callback that allows you to modify the blob request
onBeforeStorageRequest ({ id: string, file: File, xhr: XMLHttpRequest }) => mixed
A callback that allows you to modify the storage request
onSuccess* (string[]) => mixed
The callback that will be called with the signed ids of the files after the upload is complete
origin { host?: string, port?: string, protocol?: string }
The origin of your rails server. Defaults to where your React app is running
render* RenderProps => React.Node
Render props

react-activestorage-provider's People

Contributors

cbothner avatar derigible avatar mikekotte avatar inconduit avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.