Skip to content

Instantly share code, notes, and snippets.

@antonioiksi
Created November 6, 2017 13:21
Show Gist options
  • Save antonioiksi/dd22c81aba53ce976448b15d749487a0 to your computer and use it in GitHub Desktop.
Save antonioiksi/dd22c81aba53ce976448b15d749487a0 to your computer and use it in GitHub Desktop.
react read from file
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
this.handleFileSelect = this.handleFileSelect.bind(this);
}
displayData(content) {
this.setState({data: content});
}
handleFileSelect(evt) {
let files = evt.target.files;
if (!files.length) {
alert('No file select');
return;
}
let file = files[0];
let that = this;
let reader = new FileReader();
reader.onload = function(e) {
that.displayData(e.target.result);
};
reader.readAsText(file);
}
render() {
const data = this.state.data;
return (
<div>
<input type="file" onChange={this.handleFileSelect}/>
{ data && <p> {data} </p> }
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment