Created
July 8, 2016 01:54
-
-
Save rubenrangel/53252d9b60ff35d63f25592da5097073 to your computer and use it in GitHub Desktop.
Image upload React component.
This file contains hidden or 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
import React, { Component, PropTypes } from 'react'; | |
export default class ImageInput extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
src: props.src ? props.src : null, | |
} | |
this.handleOnChange = this.handleOnChange.bind(this); | |
} | |
static propTypes = { | |
src: PropTypes.string, | |
} | |
handleOnChange(e) { | |
const file = e.target.files[0]; | |
// User opened up file upload and canceled | |
if (file === undefined) { | |
return; | |
} | |
const { onChange } = this.props; | |
const reader = new FileReader(); | |
reader.onload = (e) => { | |
this.setState({ | |
src: e.target.result | |
}); | |
onChange(e.target.result); | |
} | |
reader.readAsDataURL(file); | |
} | |
render() { | |
return ( | |
<div> | |
<input | |
type="file" | |
accept=".jpg,.png" | |
onChange={this.handleOnChange} | |
/> | |
<div> | |
<div> | |
Upload an Image | |
</div> | |
</div> | |
<img | |
src={this.state.src} | |
/> | |
</div> | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This could also be made into a stateless component easily, by just relying on the
src
prop.