All Projects → cbothner → React Activestorage Provider

cbothner / React Activestorage Provider

Licence: mit
A React component that allows easy file upload using ActiveStorage

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to React Activestorage Provider

Docker Rails
Dockerize Rails 6 with ActionCable, Webpacker, Stimulus, Elasticsearch, Sidekiq
Stars: ✭ 856 (+739.22%)
Mutual labels:  rails, file-upload
Material design lite Sass
Google's Material Design Lite with Material Icons and Roboto font for Ruby applications
Stars: ✭ 100 (-1.96%)
Mutual labels:  rails
Vets Api
API powering VA.gov
Stars: ✭ 95 (-6.86%)
Mutual labels:  rails
Yabeda Rails
Yabeda plugin to collect basic metrics for Rails applications
Stars: ✭ 99 (-2.94%)
Mutual labels:  rails
Druid On Rails
Rails learning Hub, related to Ruby, Rails and everything in between
Stars: ✭ 96 (-5.88%)
Mutual labels:  rails
Splits Io
a speedrunning data store, analysis engine, and racing platform
Stars: ✭ 99 (-2.94%)
Mutual labels:  rails
Validates timeliness
Date and time validation plugin for ActiveModel and Rails. Supports multiple ORMs and allows custom date/time formats.
Stars: ✭ 1,319 (+1193.14%)
Mutual labels:  rails
Simple recommender
A simple recommendation engine for Rails/Postgres
Stars: ✭ 101 (-0.98%)
Mutual labels:  rails
Test track
Server app for the TestTrack multi-platform split-testing and feature-gating system
Stars: ✭ 100 (-1.96%)
Mutual labels:  rails
Comfy Blog
Blog Engine for ComfortableMexicanSofa (Rails 5.2+)
Stars: ✭ 98 (-3.92%)
Mutual labels:  rails
Sr mini
A single file Rails app that will have you running a StimulusReflex and CableReady demo in just 2 steps.
Stars: ✭ 98 (-3.92%)
Mutual labels:  rails
Active record replica
Redirect ActiveRecord (Rails) reads to replica databases while ensuring all writes go to the primary database.
Stars: ✭ 96 (-5.88%)
Mutual labels:  rails
Simpacker
Use modern JavaScript build system in Rails.
Stars: ✭ 100 (-1.96%)
Mutual labels:  rails
Recommendable
👍👎 A recommendation engine using Likes and Dislikes for your Ruby app
Stars: ✭ 1,340 (+1213.73%)
Mutual labels:  rails
Graphql devise
GraphQL interface on top devise_token_auth
Stars: ✭ 100 (-1.96%)
Mutual labels:  rails
Resubject
Resubject makes easy to decorate your objects
Stars: ✭ 94 (-7.84%)
Mutual labels:  rails
Stratify
Rails + MongoDB app for building a consolidated timeline of your data from disparate sources (e.g., Twitter, GitHub, Foursquare, etc.)
Stars: ✭ 97 (-4.9%)
Mutual labels:  rails
Lol dba
lol_dba is a small package of rake tasks that scan your application models and displays a list of columns that probably should be indexed. Also, it can generate .sql migration scripts.
Stars: ✭ 1,363 (+1236.27%)
Mutual labels:  rails
Pong
Two player Pong reinvented using Vue.js and Rails w/ Action Cable
Stars: ✭ 101 (-0.98%)
Mutual labels:  rails
Activerecord Clean Db Structure
Automatic cleanup for the Rails db/structure.sql file (ActiveRecord/PostgreSQL)
Stars: ✭ 101 (-0.98%)
Mutual labels:  rails

react-activestorage-provider

NPM Build Status CodeClimate Maintainability CodeClimate Coverage

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 in order to, for example, provide other attributes, see the lower level DirectUploadProvider.)

import ActiveStorageProvider from 'react-activestorage-provider'

// ...

return (
  <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
directUploadsPath string
The direct uploads path on your Rails app, if you’ve overridden ActiveStorage::DirectUploadsController
endpoint* { path: string, model: string, attribute: string, method: string, host?: string, port?: string, protocol?: string }
The details for the request to attach the file
headers {[key: string]: string}
Optional headers to add to request, can also be used to override default headers
multiple boolean (false)
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

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. Then, you can create or update your model as you need.

function PostForm() {
  function handleAttachment(signedIds) {
    const body = JSON.stringify({ post: { title: ..., images: signedIds }})
    fetch('/posts.json', { method: 'POST', body })
  }

  return (
    <DirectUploadProvider multiple onSuccess={handleAttachment} render={...} />
  )
}

DirectUploadProvider is a named export, so

import { DirectUploadProvider } from 'react-activestorage-provider'

and use it with the following props:

Prop (*required) Description
directUploadsPath string
The direct uploads path on your Rails app, if you’ve overridden ActiveStorage::DirectUploadsController
headers {[key: string]: string}
Optional headers to add to request
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
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].