Skip to content

Instantly share code, notes, and snippets.

@pieterv
Last active January 4, 2016 05:19
Show Gist options
  • Save pieterv/8574157 to your computer and use it in GitHub Desktop.
Save pieterv/8574157 to your computer and use it in GitHub Desktop.
/** @jsx React.DOM */
'use strict';
// Libs
var React = require( 'react' );
var uniqueIdCount = 0;
/**
* Generate a unique id
*
* @param {?string} prefix Options prefix for the id
* @returns {string}
*/
function uniqueId( prefix ) {
uniqueIdCount += 1;
return ( prefix || '' ) + uniqueIdCount;
}
var FileSelectButton = React.createClass( {
props: {
fileAccepts: React.PropTypes.string, // only images -> "image/*"
multiple: React.PropTypes.boolean,
onFilesSelect: React.PropTypes.func
},
getInitialState: function() {
return {
uniqueId: uniqueId( 'reactFileSelectButton' )
};
},
render: function() {
var buttonStyle = {
position: 'relative'
};
return this.transferPropsTo(
<label style={buttonStyle} htmlFor={this.state.uniqueId}>
{this.renderFileInput()}
{this.props.children}
</label>
);
},
renderFileInput: function() {
var inputStyle = {
position: 'absolute',
width: 0,
height: 0,
margin: 0,
padding: 0
};
return (
<input
ref="fileHolder"
name={this.state.uniqueId}
id={this.state.uniqueId}
type="file"
accept={this.props.fileAccepts}
style={inputStyle}
multiple={this.props.multiple}
onChange={this.handleFilesSelect} />
);
},
handleFilesSelect: function( e ) {
if ( this.props.onFilesSelect ) {
this.props.onFilesSelect( e.target.files );
this.refs.fileHolder.getDOMNode().value = '';
}
}
} );
module.exports = FileSelectButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment