How to download part of a React Component?

I am creating a website builder using React and I want to be able to download the content of this component under the preview-container class. MainWebsite contains multiple descendants and components.

export default function PreviewContainer({
    selectItem
}) {
    return (
        <div className="preview-container" >
            <div className="preview">
                <MainWebsite selectItem={selectItem}/>
            </div>
        </div>
    )
}

I tried using

function onClick() {
        var pageHTML = document.querySelector('.preview-container');
        var tempEl = document.createElement('a');
        tempEl.href = 'data:attachment/text,' + encodeURI(pageHTML);
        tempEl.target = '_blank';
        tempEl.download = 'thispage.html';
        tempEl.click();
    }

This downloads a page that just says [object HTMLDivElement] in its content Note though that I want to download this component with the css and js included

Answer

You can’t download an abstract element.

You’ll need the inner or outer HTML of the element, depending on your requirements. (You could also use ReactDOMServer.renderToString().)

Additionally, you should use a blob URL, since the HTML could be quite large and thus awkward to put in a data URL.

If you use a blob URL, it needs to be revoked (to release memory). Some browsers require an anchor element to be in the DOM when “clicked”, so that needs to be removed too. Since there’s no event for “download complete”, there’s a simple timeout for 2 seconds.

function onClick() {
  const pageHTML = document.querySelector(".preview-container").outerHTML;
  const blob = new Blob([pageHTML], { type: "text/html" });
  const url = URL.createObjectUrl(blob);
  const tempEl = document.createElement("a");
  document.body.appendChild(tempEl);
  tempEl.href = url;
  tempEl.download = "thispage.html";
  tempEl.click();
  setTimeout(() => {
    URL.revokeObjectUrl(url);
    tempEl.parentNode.removeChild(tempEl);
  }, 2000);
}