Created
November 6, 2017 13:21
-
-
Save antonioiksi/dd22c81aba53ce976448b15d749487a0 to your computer and use it in GitHub Desktop.
react read from file
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 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