|
| 1 | +import React, { Component } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import classnames from 'classnames'; |
| 4 | + |
| 5 | +class FileInput extends Component { |
| 6 | + constructor(props) { |
| 7 | + super(props); |
| 8 | + } |
| 9 | + |
| 10 | + state = { |
| 11 | + placeholder: this.props.placeholder, |
| 12 | + }; |
| 13 | + |
| 14 | + static propTypes = { |
| 15 | + /** |
| 16 | + * `accept` attribute for `input="file"`. |
| 17 | + */ |
| 18 | + accept: PropTypes.string, |
| 19 | + |
| 20 | + /** |
| 21 | + * Additional CSS classes. |
| 22 | + */ |
| 23 | + className: PropTypes.string, |
| 24 | + |
| 25 | + /** |
| 26 | + * Make file input `disabled`. |
| 27 | + */ |
| 28 | + disabled: PropTypes.bool, |
| 29 | + |
| 30 | + /** |
| 31 | + * Take up full width of parent element. |
| 32 | + */ |
| 33 | + fill: PropTypes.bool, |
| 34 | + |
| 35 | + /** |
| 36 | + * Use large file input. |
| 37 | + */ |
| 38 | + large: PropTypes.bool, |
| 39 | + |
| 40 | + /** |
| 41 | + * Accept multiple files. |
| 42 | + */ |
| 43 | + multiple: PropTypes.bool, |
| 44 | + |
| 45 | + /** |
| 46 | + * Callback used when user selects a file. |
| 47 | + * @param {array} files - array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects. |
| 48 | + * @param {SyntheticEvent} e |
| 49 | + */ |
| 50 | + onChange: PropTypes.func, |
| 51 | + |
| 52 | + /** |
| 53 | + * File input placeholder. |
| 54 | + */ |
| 55 | + placeholder: PropTypes.string, |
| 56 | + }; |
| 57 | + |
| 58 | + static defaultProps = { |
| 59 | + accept: '*', |
| 60 | + className: '', |
| 61 | + disabled: false, |
| 62 | + fill: false, |
| 63 | + large: false, |
| 64 | + multiple: false, |
| 65 | + onChange: (files, e) => {}, |
| 66 | + placeholder: 'Choose file...', |
| 67 | + }; |
| 68 | + |
| 69 | + handleChange = e => { |
| 70 | + const files = [...e.target.files]; |
| 71 | + const fileNames = files.map(f => f.name); |
| 72 | + this.setState({ |
| 73 | + placeholder: fileNames.length |
| 74 | + ? fileNames.join(', ') |
| 75 | + : this.props.placeholder, |
| 76 | + }); |
| 77 | + this.props.onChange(files, e); |
| 78 | + }; |
| 79 | + |
| 80 | + render() { |
| 81 | + const { accept, className, disabled, fill, large, multiple } = this.props; |
| 82 | + return ( |
| 83 | + <label |
| 84 | + className={classnames( |
| 85 | + 'pt-file-upload', |
| 86 | + { 'pt-fill': fill }, |
| 87 | + { 'pt-large': large }, |
| 88 | + className |
| 89 | + )} |
| 90 | + > |
| 91 | + <input |
| 92 | + multiple={multiple} |
| 93 | + accept={accept} |
| 94 | + type="file" |
| 95 | + disabled={disabled} |
| 96 | + onChange={this.handleChange} |
| 97 | + /> |
| 98 | + <span className="pt-file-upload-input">{this.state.placeholder}</span> |
| 99 | + </label> |
| 100 | + ); |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +export default FileInput; |
0 commit comments