Rendering HTML files in an Express/React/React Router application

Damien Cosset - Mar 27 '19 - - Dev Community

Hello everyone. Never posted here about a code problem, but I am really stuck :D

I have an code editor application. I can open files, edit them and save them. At one point, I want to preview the html files in a new tab in order to see the changes I have made. Now, these are full page html, like so:

<html>
    <head>
        <link ... />
        <script src="..." />
    </head>
    <body>...</body>
</html>

I can get the HTML content but I can't find a way to correctly load the HTML in a new tab.

I tried to use a window.open(filePath). The problem is that I get a localhost:3000/filePath and the HTML would be rendered inside the React application markup, which is not what I want.

I tried to use some iframe but that failed miserably.

I believe, and I may be wrong, that I need to bypass the react-router directive to use response.renderFile from Express. How would I manage that?

So, make a post request with the file path, open a new tab and render from express the HTML content. Right?

Any tips? :)

EDIT:

Kinda solved my problem. I'm using the following code:

childUrl = window.open('/preview', '_blank')
childUrl.document.open('text/html', 'replace')
childUrl.document.write(htmlContent)

I still have a little issue with this. The path to the external files ( scripts and links ) need to start from the top level and can't be relative. So, I guess it's solved?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .