skip to Main Content

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
enter image description here

Here is my file directory:

enter image description here

2

Answers


  1. You need to make index.html accessible from your Next.js app. If index.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 the public folder. Then, the fetch URL should correctly point to this file as /index.html.

    Login or Signup to reply.
  2. index.html file located in pages folder is inaccessible for your app.

    Here is what you could try to do to make it downloadable:

    1. move to your page (index.html file) to public folder. rename file to template.html);
    2. modify const response = await fetch('index.html'); to const response = await fetch('/template.html');.
      `
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search