-
-
Save designviacode/cef11b795a5c9023c6c8aca07113c1cb to your computer and use it in GitHub Desktop.
React Image Uploading Component with Image Preview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ImageUpload extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
file: '', | |
imagePreviewUrl: '' | |
}; | |
this._handleImageChange = this._handleImageChange.bind(this); | |
this._handleSubmit = this._handleSubmit.bind(this); | |
} | |
_handleSubmit(e) { | |
e.preventDefault(); | |
// TODO: do something with -> 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} />); | |
} | |
return ( | |
<div> | |
<form onSubmit={this._handleSubmit}> | |
<input type="file" onChange={this._handleImageChange} /> | |
<button type="submit" onClick={this._handleSubmit}>Upload Image</button> | |
</form> | |
{$imagePreview} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment