0

I want to simply inline a HTML file in React by doing something like this :

import someFile from './aHtmlFile.html';

const Example = (props) => {
    return (
        <div dangerouslySetInnerHTML={ {__html: someFile} } />
    );
}

However, I don't want to install Webpack only because of this. Are there any other ways of doing this easily ?

2
  • You could save the HTML file as a string in a variable and and set it that way, instead of importing it. Commented Aug 19, 2022 at 19:37
  • Yes, good point, I might go for that actually Commented Aug 19, 2022 at 20:00

1 Answer 1

1

You can load the file via fetch and save it into a state.

import { useState } from "react";
import { useEffect } from "react";

export const Example = (props) => {
  const [content, setContent] = useState("");

  useEffect(() => {
    fetch("./aHtmlFile.html").then((response) => {
      setContent(response.data);
    });
  }, []);

  return <div dangerouslySetInnerHTML={{ __html: content }} />;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, so I can actually fetch the file. Nice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.