perspective/perspective

View on GitHub
lib/client/components/file-input.react.js

Summary

Maintainability
A
25 mins
Test Coverage
var React = require('react');

var FileInput = React.createClass({
  propTypes: {
    // example: 'image.*'
    accepts: React.PropTypes.string.isRequired
  },

  getInitialState: function() {
    return {file: null};
  },

  onFile: function(e) {
    e.preventDefault();

    var files;
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }

    var file = files[0];
    if (!file.type.match(this.props.accepts)) {
        return;
    }

    var uploader = this;
    var reader = new FileReader(); // jshint ignore:line
    reader.onload = (function(file) {
      return function(e) {
        var fileData = e.target.result;
        uploader.setState({file: fileData});
        if(uploader.props.onInput) {
          uploader.props.onInput(fileData);
        }
      };
    })(file);

    // Read in the image file as a data URL.
    reader.readAsDataURL(file);
  },

  render: function() {
    return (
      <div>
        <input type="file" onChange={this.onFile} />
      </div>
    );
  }
});

module.exports = FileInput;