Skip to content

Instantly share code, notes, and snippets.

@husek
Created September 5, 2016 15:33
Show Gist options
  • Save husek/7a0309acb5fc406c47d1de528e674bfb to your computer and use it in GitHub Desktop.
Save husek/7a0309acb5fc406c47d1de528e674bfb to your computer and use it in GitHub Desktop.
Material UI Upload Button
import React, { PropTypes, Component } from 'react';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
export default class UploadButton extends Component {
static propTypes = {
button: PropTypes.oneOf(['flat', 'raised']).isRequired,
raised: PropTypes.bool,
label: PropTypes.string.isRequired,
disabled: PropTypes.bool,
multiLabel: PropTypes.string,
multiple: PropTypes.bool,
inputName: PropTypes.string,
inputRef: PropTypes.string,
onChange: PropTypes.func,
valueLink: PropTypes.object
};
constructor(props) {
super(props);
this.state = {
fileName: this.props.label
};
};
_getFileName = (event) => {
if (event.target.files[0].name) {
this.setState({
fileName: `.../${event.target.files[0].name}`
});
}
if (this.props.onChange) this.props.onChange(event);
};
_multipleHandler = (event) => {
const multipleLabel = this.props.multiLabel || 'Files Selected';
if (event.target.files.length > 0) {
this.setState({
fileName: `${event.target.files.length} ${multipleLabel}`
});
}
if (this.props.onChange) this.props.onChange(event);
};
render() {
const {
button,
label,
multiLabel,
multiple,
inputName,
inputRef,
onChange,
...otherProps
} = this.props;
let inputElement;
let currentLabel;
const styles = {
inputFile: {
cursor: 'pointer',
height: '100%',
position: 'absolute',
top: 0,
right: 0,
zIndex: 2,
fontSize: 50,
opacity: 0
}
};
const inputProps = {
style: styles.inputFile,
ref: inputRef || 'input',
name: inputName || 'input'
};
if (this.props.hasOwnProperty('valueLink')) {
inputProps.valueLink = this.props.valueLink;
}
if (!this.props.disabled) {
if (!multiple) {
inputProps.onChange = this._getFileName;
} else {
inputProps.onChange = this._multipleHandler;
inputProps.multiple = 'multiple';
}
inputElement = (
<input type="file" {...inputProps} />
);
}
currentLabel = this.state.fileName;
let component;
if (button === 'flat') {
component = (
<FlatButton {...otherProps}>
{currentLabel}
{inputElement}
</FlatButton>
);
} else {
component = (
<RaisedButton {...otherProps}>
{currentLabel}
{inputElement}
</RaisedButton>
);
}
return (
<span>
{component}
</span>
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment