DEV Community

Cover image for 4 steps to render HTML file in React
shrey vijayvargiya
shrey vijayvargiya

Posted on

4 steps to render HTML file in React

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();
};
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

--

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",
 },],
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
thi3rry profile image
Thierry Poinot

You should change your title by "4 steps to render html with Next.js"
Basically, react is JavaScript framework and needs an html page to be run.

Collapse
 
shreyvijayvargiya profile image
shrey vijayvargiya

Correct, but we are moving ahead of it in 2022, when it comes to working with Nextjs we hardly deal with witing HTML code, if static is required, we got for mdx rather thatn HTML and most of the time, we prefer to use JSX.
That is why I cover a entire dedicated story to tell how to deal with basic HTML file in nextjs repository.