Skip to content

Instantly share code, notes, and snippets.

@denisdenes
Created June 23, 2019 15:55
Show Gist options
  • Save denisdenes/757997f58f73de6e9a1413c821262984 to your computer and use it in GitHub Desktop.
Save denisdenes/757997f58f73de6e9a1413c821262984 to your computer and use it in GitHub Desktop.
import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col } from "../Grid";
import { GalleryUploaderCard } from "./galleryUploaderCard";
export class GalleryUploader extends React.Component {
state = { imagesBase64: [] };
componentDidUpdate(prevProps, prevState, snapshot) {
if ( this.state.imagesBase64 !== prevState.imagesBase64 ) {
this.props.sendImages(this.state.imagesBase64);
}
}
render() {
return (
<Row>
<Col>
<Row className="justify-content-center">
<Col className="text-center">
<label htmlFor="imageUpload" className="btn btn-primary btn-block" style={ { cursor: 'pointer' } }>
<span>Select images...</span>
</label>
<input type="file"
multiple
id="imageUpload"
style={ { display: "none" } }
onChange={ this.addImages }
/>
</Col>
</Row>
<Row className="mx-0">
{ this.state.imagesBase64.map((image, i) => (
<GalleryUploaderCard
imgSrc={ image }
iterator={ i }
deleteImage={ this.handleDeleteImageFromState }
key={ Math.random() }
/>
)) }
</Row>
</Col>
</Row>
);
}
addImages = async e => {
e.persist();
if ( e.target.files && e.target.files.length > 0 ) {
for(let i = 0; i < e.target.files.length; i++) {
this.readFile(e.target.files[ i ])
.then((res) => {
this.setState(prevState => ({
imagesBase64: [ ...prevState.imagesBase64, res]
}));
})
.catch((err) => console.log(err));
}
}
};
readFile = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', () => resolve(reader.result), false);
reader.addEventListener('error', error => reject(error));
reader.readAsDataURL(file)
})
};
handleDeleteImageFromState = (image) => {
this.setState(prevState => {
const imagesBase64 = prevState.imagesBase64.filter((item, j) => image !== j);
return { imagesBase64 }
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment