0

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;
1
  • You can use iframe for that. <iframe src={src} height={someHeight} width={someWidth} id = "frame" /> Here src prop value would be your URL Commented Aug 5, 2021 at 11:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

unable to see anything in console.
Please check the url, whether the data is available there or it requires some permission (like login credentials or password) to read data from the url
Data is available in the text file and it doesn't require any permission to access it. You may check the link given in the sandbox code given above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.