Skip to content

Instantly share code, notes, and snippets.

@rubenrangel
Created July 8, 2016 01:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubenrangel/53252d9b60ff35d63f25592da5097073 to your computer and use it in GitHub Desktop.
Save rubenrangel/53252d9b60ff35d63f25592da5097073 to your computer and use it in GitHub Desktop.
Image upload React component.
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>
);
}
};
@rubenrangel
Copy link
Author

This could also be made into a stateless component easily, by just relying on the src prop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment