ReactJs Image upload and preview it

I will explain how to select image and preview it using FileReader(). FileReader is used to asynchronously read the contents of the file and store in user’s machine usinf File or Blob object. So we can use this object to display the uploaded image.

<div id="react-root"></div>
ReactDom.render(
	<FileField />,
	document.getElementById('react-root')
);
var FileField = React.createClass({
	_changeEvent:function(e){
		e.preventDefault();
        
		let reader = new FileReader();
        
		let file = e.target.files[0];
        
		var _this = this;
        
		reader.onloadend = function() {
            
			_this.refs.preview.innerHTML=(<img src="{reader.result}/" />);
		}
        
		reader.readAsDataURL(file);
	},
	render:function(){
		return(
			<div>
			        <input type="file" onChange={this._changeEvent} />
				<div ref="preview"></div>
			</div>
		)
	}
});

Leave a Reply

Your email address will not be published. Required fields are marked *