I want to display content from an HTML file in next.js. I learned that I can use dangerouslySetInnerHTML in App.js to achieve this.
However, I keep getting a blank white screen when using it. I’ve tried sending the GET request to the index.html file but I keep getting a white screen.
App.js
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [htmlContent, setHtmlContent] = useState('');
useEffect(() => {
async function fetchHtml() {
try {
const response = await fetch('index.html');
const html = await response.text();
setHtmlContent(html);
} catch (error) {
console.error('Error fetching HTML file:', error);
}
}
fetchHtml();
}, []);
return (
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
);
}
export default MyComponent;
My index.html just has boilerplate code and <p>Hello World</p>
, so it should be showing the text on the page, however I get this white screen.
here is the white screen I’m getting
Here is my file directory:
2
Answers
You need to make
index.html
accessible from your Next.js app. Ifindex.html
isn’t in the public directory, the fetch call won’t be able to access it because it’s not exposed as a static file.Move your
index.html
to thepublic
folder. Then, the fetch URL should correctly point to this file as/index.html
.index.html
file located inpages
folder is inaccessible for your app.Here is what you could try to do to make it downloadable:
public
folder. rename file totemplate.html
);const response = await fetch('index.html');
toconst response = await fetch('/template.html');
.`