4 steps to render HTML file in React
shrey vijayvargiya
Posted on August 24, 2022
01
I am using the Next.js repository so you need to install that, if you are new to it, here is the link to get started.
https://medium.com/nerd-for-tech/you-really-need-to-migrate-to-next-js-ee646a9982ab
02
Once the repository is installed, we will deal with serverless functions(If new), followed by adding the following code to the serverless function.
I am creating a sample hello API inside the pages/api directory that will return an HTML file in response.
import fs from "fs";
const filename = "/portfolio/index.html";
module.exports = async(req, res) => {
res.setHeader("Content-Type", "text/html, charset=utf-9");
res.write(await fs.readFileSync(filename, "utf-8"));
res.end();
};
03
Adding an HTML file is the third step.
pages directory in the root directory is the location for all static files in the next.js repository.
Add the HTML code to the profile.html file.
<html>
<head>
<title>Example</title>
</head>
<body>
<p>This is an example of a simple HTML page with one paragraph.</p>
</body>
</html>
--
04
This is a crucial step, we will now tell next.js to show render the HTML code inside the index.html file and return them in the api/profile page.
When the user opens the profile page, api/profileendpoint will get the request to render the profile HTML file on the website.
We will tell next.js to configure the request using the proxy URL concept and that will be achieved by adding followed code in the next.config.js file in the root directory.
module.exports = () => {
rewrites: async () => [{
source: "/public/portfolio/index.html",
destination: "/pages/api/portfolio.js",
},],
}
Now our profile.html route will simply render an HTML file.
05
That's it for today, until next time, have a good, day.
Our website iHateReading
Posted on August 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.