Preserve appearance when saving .html document (React)

Below is a simplified version of my React component:

export class SomePage extends Component {

  downloadAsHTML() {
    const element = document.createElement("a");

    const file = new Blob([document.getElementById('second-child-div').outerHTML], {
      type: "text/html"
    });

    element.href = URL.createObjectURL(file);
    element.download = "file.html";
    document.body.appendChild(element);
    element.click();
  }

  render () {
    return (
      <>
        <div className="first-child-div">Stuff here</div>
        <div id="second-child-div" onClick={() => this.downloadAsHTML()}>
           <span className="some-other-styling-here">
              <h1>Title</h1>
              <p>Paragraph</p>
              More things here
           </span>
           More html elements, nested styling, and text here
        </div>
      </>
    )
  }

}

When the user clicks on second-child-div and the div gets downloaded as an .html file, I want the downloaded .html file to retain the styling of all the classNames and html selectors (like #second-child-div h1 that would be in .css). What is the best way to do this?

One approach I'm considering is creating another file called Styles.js:

const Styles = {
  container: {
    'padding': '30px',
    'border'
  },
  anotherContainer:  {
    'color': 'blue',
    'background': 'yellow'
  }
  containerH1: {
    'font-size': '20px'
  }
  containerParagraph: {
    'font-size': '20px'
  },
}

export default Styles;

and then import it like so:

import "Styles" from "./Styles.js"

//in second-child-div:

<div id="second-child-div" style={Styles.container} onClick={() => this.downloadAsHTML()}>
   <span style={Styles.anotherContainer}>
      <h1 style={Styles.containerH1}>Title</h1>
      <p style={Styles.containerParagraph}>Paragraph</p>
       More things here
   </span>
   More html elements, nested styling, and text here
</div>

In my actual application, I have numerous styling rules with css selectors and so forth. What would be the most efficient way to handle this?

Answer â„–1

One way to handle the CSS loading when a button is clicked is to embed the CSS directly into the HTML file within <style> tags before saving it.

This method may seem forceful as it doesn't selectively pick styles for the exported element, but instead captures all of them.

const downloadAsHTML = () => {
  const element = document.createElement("a");

  const domNodeToSave = document.getElementById("second-child-div");
  const modifiedDomNodeToSave = domNodeToSave.cloneNode(true);
  modifiedDomNodeToSave.style.margin =
    "10px"; // example modificaiton

  const htmlSnippet = modifiedDomNodeToSave.outerHTML;

  const styleSheets = document.styleSheets;

  let allStyles = "";

  for (let i = 0; i < styleSheets.length; i++) {
    const styleSheet = styleSheets[i];

    const rules = styleSheet.cssRules;

    for (let j = 0; j < rules.length; j++) {
      const rule = rules[j];

      allStyles += rule.cssText + "\n";
    }
  }

  const styleBlock = `<style>${allStyles}</style>`;
  htmlSnippet += styleBlock;

  const file = new Blob([htmlSnippet], {
    type: "text/html",
  });

  element.href = URL.createObjectURL(file);
  element.download = "file.html";
  document.body.appendChild(element);
  element.click();
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to include a meta property with the value "og:locale"?

There have been multiple articles discussing how to properly add the meta og:locale. I want to know for sure which format is correct, is it 'en_US' or 'en-US'? Are they both valid? On my website, I added it using this format: <meta ...

Tips for arranging left and right elements in a row of three items?

Adding a second Header (from react-native-element 3.4.2) to a React Native 0.70 app involves placing it under the first Header, with its centerComponent pointing to a search bar that spans only one line. Below is the code snippet: import { Header } from &a ...

Utilize Sass variables to store CSS font-size and line-height properties for seamless styling management

How can I save the font size and line height in a Sass variable, like so: $font-normal: 14px/21px; When using this declaration, I notice that a division occurs as explained in the Sass documentation. Is there a way to prevent this division from happening ...

Using the last child as a parent element in Selenium with JavaScript

I am trying to access the input element of the last child in this code snippet. Specifically, I want to retrieve the text Text Reply - Delete. <div class="priority-intent-div"> <div class="row add-priority-intent-div"> ...

Exploring the process of including cube quantities in three.js code

In my current project, I am facing a challenge of incorporating multiple spheres into the scene. Initially, there were only three cubes present, but now I need to include around 10 spheres that are evenly spaced from each other and are rotating at varying ...

Displaying an array of data from a list of arrays in AngularJS' session storage

Whenever a button is clicked, the data will be pushed into an array list and stored in session storage. var data = [ 'name':"name", 'id'=1 ]; var arrayList = new Array; arrayList.push(data); sess ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

How come an image with position:absolute doesn't have a height? Even though I can clearly see its height in the browser

I'm perplexed as to why a div with display:block won't position itself below another div with the same style. Here's my code: .container{ display: block; position: relative; } .container img{ width: 100%; position: absolute; t ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

Retrieving text content from an HTML element with Jsoup for web page manipulation

My task involves extracting text content from a specific HTML element <span class="adr" style="float: none !important;"> <span class="street-address" style="float: none !important;">18, Jawaharlal Nehru Road, </span> ...

Simulating a traditional table scroll function on a window using virtualization

I am currently attempting to incorporate a virtualized table in react using react–virtualized, but I am facing issues with the rendering of the table. I am seeking to understand the root cause for this problem as well as find solutions for other overlapp ...

Ways to recycle functional elements in Next.js 13 Server Components

Encountering a problem trying to separate the logic from the component due to this error message: Error: Event handlers cannot be passed to Client Component props. <textarea rows={18} placeholder=... onInput={function}> ...

Controlling Camera Movement in THREE.js Using Mouse with Constraints

Is there a way to move the camera around my JSON scene using only mouse movements? I want the camera to follow the direction of the mouse without the need for clicking and dragging. Currently, I have a partially functioning solution, but it's not meet ...

The full width of the div exceeds the parent's width, resulting in the box size being ineffective

I'm experiencing an issue where my cover is wider than my element and content. It seems to be covering the gunter, but I've tried using background-clip: content-box; and box-sizing: border-box;, which haven't resolved the problem. I also wan ...

When an HTML page is hosted on an external server, its formatting may

I recently put together an HTML page that incorporates some CSS and two simple highcharts from highcharts.com. After testing the page on my local machine and being satisfied with the outcome, I transferred it to a server on our internal network to make it ...

Is there a way to maintain the case when dynamically creating a Mui icon using React.createElement instead of React lowercasing the element?

Obtaining the service.icon from JSON results in the following structure: [ { "icon": "AdminPanelSettingsIcon", } ] Incorporating React.createElement() as shown below: data.map((service) => { let icon = React.createElement( ...

What is the method to retrieve a value from a function call when a button is pressed?

Exploring the world of JavaScript, I'm currently working on a small program in React Native. My goal is to create a function SampleFunction2 that returns census data, and then render it on a FlatList when a button is pressed. Am I missing something by ...

Implementing custom styles in JavaScript according to the specific browser or platform

When it comes to adding multiple css styles to a dom element and ensuring compatibility across different browsers, which approach is more optimal for performance? Combining all prefixed css properties together, allowing the browser to decide which one ...

Input form sending information to an incorrect destination URL

I'm struggling to get my form to pass a parameter to a link in the desired format: index.php?action=2&parameter=value Currently, it is only passing the parameter like this: index.php?parameter=value Here's the code I have been using : &l ...

Choose and manipulate a set of elements using Jquery

Below is a piece of code I have: <div class="timeline"> <div class="timeslice" data-tid="360"></div> <div class="timeslice" data-tid="360"></div> <div class="timeslice" data-tid="360"></div> <di ...