How to read in local file in react [duplicate]

2 weeks ago 8
ARTICLE AD BOX

What's going wrong is that fetch() is not finding the file at localFilePath, and the React is responding to that 404 with index.html instead — this is standard SPA behavior where all unmatched routes fall back to the HTML shell. So you're not getting a network error, you're silently getting the wrong file entirely. The reason why you read You need to enable JavaScript... it's because that's the <noscript> part of the index.html.

There are two things to fix:

1. Put the file in /public

Files in src are processed by the bundler and not directly servable via URL. Only files in the /public folder can be fetched at runtime. Place your file there, e.g. /public/demo-content.html.

2. Reference it correctly

Don't hardcode the path as a string. Use the process.env.PUBLIC_URL variable that CRA provides:

const resp = await fetch(`${process.env.PUBLIC_URL}/demo-content.html`);

Or simply:

const resp = await fetch('/demo-content.html');

3. Also — you're missing the fetchContent() call

Your useEffect defines the async function but never calls it.

This part actually confused me.. because it still makes no sense considering the behaviour you observed. Maybe you did forget to include in the snippet you shared here?

Anyway to make sure add the invocation:

useEffect(() => { const fetchContent = async () => { const resp = await fetch('/demo-content.html'); const initialContent = await resp.text(); setValue(initialContent); }; fetchContent(); // this was missing }, []);

That's also why there were no console errors — the async function was declared but never executed(??), so nothing failed, and the alert you saw must have been from a previous run or a different code path. This part is still a mystery to me by the way.

Read Entire Article