Issue
We have a list of HTML files under the folder src/html
in a react project. Now we need to read the menu items with in the HMTL file and display them using a React component. The HTML contains element to hold the menu items also there is other section of the content as well. Can you guide me on the implementation way to display the menu from the HTML to React App?
Solution
use cheerio library.
I have extracted menu items from sample.html and passed them as a prop to MenuComponent.
App.js
import React, { useEffect, useState } from "react";
import MenuComponent from "./MenuComponent";
const App = () => {
const [menuItems, setMenuItems] = useState([]);
useEffect(() => {
const fetchMenuItems = async () => {
try {
const response = await fetch("sample.html");
const htmlContent = await response.text();
const cheerio = require("cheerio");
const $ = cheerio.load(htmlContent);
const extractedMenuItems = [];
$("nav ul li").each((index, element) => {
extractedMenuItems.push($(element).text());
});
setMenuItems(extractedMenuItems);
} catch (error) {
console.error("Error fetching or parsing HTML:", error);
}
};
fetchMenuItems();
}, []);
return (
<div>
<h1>Your React App</h1>
<MenuComponent menuItems={menuItems} />
</div>
);
};
export default App;
MenuComponent.js
import React from "react";
const MenuComponent = ({ menuItems }) => {
return (
<div>
<h2>Menu</h2>
<ul>
{menuItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
export default MenuComponent;
sample.html (It's in the public folder)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sample HTML</title>
</head>
<body>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
<div>
<h1>Main Content</h1>
<p>This is the main content of the page.</p>
</div>
</body>
</html>
If you wanna play around with the code
Answered By - Anshu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.