ProfileImageUploader.jsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { withTranslation } from 'react-i18next';
  4. import AppContainer from '../../services/AppContainer';
  5. import { createSubscribedElement } from '../UnstatedUtils';
  6. import 'react-image-crop/dist/ReactCrop.css';
  7. import ImageCropModal from './ImageCropModal';
  8. class ProfileImageUploader extends React.Component {
  9. constructor(props) {
  10. super();
  11. this.state = {
  12. show: false,
  13. src: null,
  14. croppedImageUrl: null,
  15. };
  16. this.imageRef = null;
  17. this.onSelectFile = this.onSelectFile.bind(this);
  18. this.hideModal = this.hideModal.bind(this);
  19. this.cancelModal = this.cancelModal.bind(this);
  20. this.onCropCompleted = this.onCropCompleted.bind(this);
  21. }
  22. onSelectFile(e) {
  23. if (e.target.files && e.target.files.length > 0) {
  24. const reader = new FileReader();
  25. reader.addEventListener('load', () => this.setState({ src: reader.result }));
  26. reader.readAsDataURL(e.target.files[0]);
  27. this.setState({ show: true });
  28. }
  29. }
  30. onCropCompleted(croppedImageUrl) {
  31. this.setState({ croppedImageUrl });
  32. this.hideModal();
  33. }
  34. showModal() {
  35. this.setState({ show: true });
  36. }
  37. hideModal() {
  38. this.setState({ show: false });
  39. }
  40. cancelModal() {
  41. this.hideModal();
  42. }
  43. render() {
  44. const { t } = this.props;
  45. const { croppedImageUrl } = this.state;
  46. return (
  47. <div className="ProfileImageUploader">
  48. <div className="form-group">
  49. <label className="col-sm-4 control-label">
  50. {t('Upload new image')}
  51. </label>
  52. </div>
  53. <div className="col-sm-8">
  54. {croppedImageUrl && (
  55. <img src={croppedImageUrl} className="picture picture-lg img-circle" id="settingUserPicture" />
  56. )}
  57. <input type="file" onChange={this.onSelectFile} name="profileImage" accept="image/*" />
  58. <ImageCropModal
  59. show={this.state.show}
  60. src={this.state.src}
  61. onModalClose={this.cancelModal}
  62. onCropCompleted={this.onCropCompleted}
  63. />
  64. </div>
  65. </div>
  66. );
  67. }
  68. }
  69. /**
  70. * Wrapper component for using unstated
  71. */
  72. const ProfileImageFormWrapper = (props) => {
  73. return createSubscribedElement(ProfileImageUploader, props, [AppContainer]);
  74. };
  75. ProfileImageUploader.propTypes = {
  76. t: PropTypes.func.isRequired, // i18next
  77. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  78. };
  79. export default withTranslation()(ProfileImageFormWrapper);