wix-style-react
Version:
99 lines (83 loc) • 2.89 kB
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
import { dataHooks } from './constants';
/** A wrapper component to support native file upload */
class FileUpload extends React.PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
render() {
const {
dataHook,
className,
children,
multiple,
accept,
capture,
name,
onChange,
} = this.props;
return (
<label className={className} data-hook={dataHook}>
{children({
openFileUploadDialog: event => {
// Open the file upload dialog
this.inputRef.current.click();
// In case the click event comes from a non-button element
if (event) {
event.preventDefault();
}
},
})}
{/* An invisible input type="file" in order to open a file upload dialog */}
<input
type="file"
data-hook={dataHooks.input}
style={{ display: 'none' }}
ref={this.inputRef}
multiple={multiple}
accept={accept}
capture={capture === 'none' ? null : capture}
name={name}
onChange={event => onChange(event.target.files)}
/>
</label>
);
}
}
FileUpload.displayName = 'FileUpload';
FileUpload.propTypes = {
/** Applies a data-hook HTML attribute that can be used in tests. */
dataHook: PropTypes.string,
/** Allows the application of a CSS class to the components’ root element. */
className: PropTypes.string,
/** Accepts any kind of component as a child item that calls out the file picker.
* ##### Syntax:
* function({ openFileUpload }): element
* * `openFileUpload`: A function that will open a file upload dialog when triggered.
* * return: A react element
*/
children: PropTypes.func.isRequired,
/** Allows you to select and upload multiple files at once. */
multiple: PropTypes.bool,
/** Defines which file types to accept (i.e. .jpeg, .gif, .png). Each format should be separated by a comma. */
accept: PropTypes.string,
/** Specifies that a new file should be captured and which camera to use to capture the image or video data.
* `Use user` for the user-facing camera and `environment` for the outward-facing camera.
* ##### Note: This only works on mobile devices;
* If your device is a desktop computer, you'll get a standard file picker.
* */
capture: PropTypes.oneOf(['user', 'environment', 'none']),
/** Specifies a form data name to be submitted along with the control value. */
name: PropTypes.string,
/** Defines a standard input onChange callback. */
onChange: PropTypes.func.isRequired,
};
FileUpload.defaultProps = {
multiple: false,
accept: '',
capture: 'user',
onChange: () => {},
};
export default FileUpload;