Reputation: 103
With code below, I am able to render the content of the local text file to the web page, but when I use a URL to get the text file to render it on the webpage, I get " "
because the state is defined null
. To render a local text file I had to use import text from './filepath.txt
. How I can render text content from a URL link?
import React, { Component } from "react";
import "./App.css";
import text from "./myText.txt";
class App extends Component {
state = { loading: true,
docText: null,
};
componentDidMount() {
fetch( text, { mode: "no-cors" }
// {
// method: "GET",
// headers: {
// "Content-Type": "application/text",
// },
// }
).then((response) => { return response.text();})
.then((data) => {
this.setState({ docText: data, loading: false });
console.log({ docText: data });
})
.catch((error) => { console.log(error);
});
}
render() {
return (
<div className="App">
<h1>Fetched Data</h1>
<div>
{this.state.loading || !this.state.docText ? (
<div>Loading...</div>
) : (
<div>
<div>{this.state.docText}</div>
</div>
)}
</div>
</div>
);
}
}
export default App;
Upvotes: 0
Views: 4887
Reputation: 517
Before rendering the content to the DOM, verify whether the file is read from the url.
Please try the below code,
fetch("https://URL/file").then((r)=>{r.text().then(d=>console.log(d))})
try steps mentioned in this question Get text from a txt file in the url
Upvotes: 2