Created
April 27, 2017 03:30
-
-
Save longsangstan/3c259ed76c25784bd17694aab05a37af to your computer and use it in GitHub Desktop.
A React component to read text 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
import React from "react"; | |
/* | |
Read a text file and out put the content. | |
Example Usage: | |
var myTxt = require("./myTxt.txt"); | |
... | |
<TextFileReader | |
txt={myTxt} | |
/> | |
*/ | |
class TextFileReader extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
text: "" | |
}; | |
} | |
componentDidMount() { | |
this.readTextFile(this.props.txt); | |
} | |
readTextFile = file => { | |
var rawFile = new XMLHttpRequest(); | |
rawFile.open("GET", file, false); | |
rawFile.onreadystatechange = () => { | |
if (rawFile.readyState === 4) { | |
if (rawFile.status === 200 || rawFile.status == 0) { | |
var allText = rawFile.responseText; | |
this.setState({ | |
text: allText | |
}); | |
} | |
} | |
}; | |
rawFile.send(null); | |
}; | |
render() { | |
return ( | |
<div> | |
{this.state.text.split("\n").map((item, key) => { | |
return <span key={key}>{item}<br /></span>; | |
})} | |
</div> | |
); | |
} | |
} | |
export default TextFileReader; |
cengugr
commented
Apr 23, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment