Skip to content

Instantly share code, notes, and snippets.

@chibaye
Created April 27, 2019 15:18
Show Gist options
  • Save chibaye/b93e863c745bdf47a4e9917a5e3166cf to your computer and use it in GitHub Desktop.
Save chibaye/b93e863c745bdf47a4e9917a5e3166cf to your computer and use it in GitHub Desktop.
React Image Preview & Upload
h3 React Image Preview & Upload Component
div#mainApp
div.centerText
span Checkout associated
a(href="http://www.hartzis.me/react-image-upload/" target="_blank") blog post
class ImageUpload extends React.Component {
constructor(props) {
super(props);
this.state = {file: '',imagePreviewUrl: ''};
}
_handleSubmit(e) {
e.preventDefault();
// TODO: do something with -> this.state.file
console.log('handle uploading-', this.state.file);
}
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
} else {
$imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
}
return (
<div className="previewComponent">
<form onSubmit={(e)=>this._handleSubmit(e)}>
<input className="fileInput"
type="file"
onChange={(e)=>this._handleImageChange(e)} />
<button className="submitButton"
type="submit"
onClick={(e)=>this._handleSubmit(e)}>Upload Image</button>
</form>
<div className="imgPreview">
{$imagePreview}
</div>
</div>
)
}
}
ReactDOM.render(<ImageUpload/>, document.getElementById("mainApp"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
h3
margin-left: 15px
.fileInput
border-bottom: 4px solid lightgray
border-right: 4px solid lightgray
border-top: 1px solid black
border-left: 1px solid black
padding: 10px
margin: 15px
cursor: pointer
.imgPreview
text-align: center
margin: 5px 15px
height: 200px
width: 500px
border-left: 1px solid gray
border-right: 1px solid gray
border-top: 5px solid gray
border-bottom: 5px solid gray
img
width: 100%
height: 100%
.previewText
width: 100%
margin-top: 20px
.submitButton
padding: 12px
margin-left: 10px
background: white
border: 4px solid lightgray
border-radius: 15px
font-weight: 700
font-size: 10pt
cursor: pointer
&:hover
background: #efefef
.centerText
text-align: center
width: 500px
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment