Issue
I am trying to display an html file inside a react component. After debugging in VS code, setHtmlContent
is called and htmlContent
is set to html string, but nothing is displayed on the screen, it should display hello
from the html in the first example. But if I remove fetch and set html to a variable in the second example, it will display hello
on the screen. Is there a mistake when I am importing the html file?
CodeSandbox: https://codesandbox.io/s/quirky-phoebe-cywd9s?file=/src/App.js
First example with fetch html.
src/assets/html/en.html
<!DOCTYPE html>
<html>
<body>
<div>
<p>Hello</p>
</div>
</body>
</html>
src/App.js
import "./styles.css";
import React, { useEffect, useState } from "react";
export default function App() {
const [htmlContent, setHtmlContent] = useState("");
useEffect(() => {
// Fetch the HTML content from a file or URL
fetch("../assets/html/en.html")
.then((response) => response.text())
.then((data) => {
setHtmlContent(data);
})
.catch((error) => {
console.error("Error fetching HTML content:", error);
});
}, []);
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}
Second example with html as variable:
src/App.js
import "./styles.css";
import React from "react";
export default function App() {
const htmlContent = `
<!DOCTYPE html>
<html>
<style>
body {
font-family: 'Roboto', sans-serif;
padding: 0px;
}
</style>
<body>
<div class="et_pb_tab_content">
<div class="page" title="Page 1">
<div class="layoutArea">
<div class="column">
<p>Hello</p>
</div>
</div>
</div>
</body>
</html>
`;
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}
Solution
Here is the working folder structure you have to set your HTML code inside a public directory path like public/assets/html/en.html
src/App.js
import React, { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [htmlContent, setHtmlContent] = useState("");
useEffect(() => {
// Fetch the HTML content from the public directory
fetch("/assets/html/en.html")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then((data) => {
setHtmlContent(data);
})
.catch((error) => {
console.error("Error fetching HTML content:", error);
});
}, []);
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}
Output:
Hope it will solve your problem.
Answered By - Isha Padalia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.