React Printing Made Easy: A Powerful Method

React Printing Made Easy: A Powerful Method

React Printing, This guide explores approaches to achieve printing functionality within React applications, Windows printing APIs made easy without using any third party library or components.

Here we use window.matchMedia() method to detect print events of windows. The window.matchMedia() method in JavaScript provides a way to check if the current state of the browser window (e.g., screen size, device orientation) matches a specific media query. Media queries are used in CSS to define different styles for different screen sizes, resolutions, or other device characteristics.

Please follow the step by step guide for the React Printing.

Index.html – Set root for the printing component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link href="./styles.css" rel="stylesheet" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <div id="print-mount" class="show"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

styles.css

@media print {
  .show {
    display: block;
  }
}

@media screen {
  .show {
    display: none;
  }
}

index.js – Render the app component

import ReactDOM from "react-dom/client";

import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

index.css

@import url("https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap");

* {
  box-sizing: border-box;
}

html {
  font-family: "Noto Sans JP", sans-serif;
}

body {
  margin: 0;
}

App.js

import MyComponent from "./Components/MyComponent.js";

function App() {
  return (
    <div>
      <MyComponent />
    </div>
  );
}

export default App;

MyComponent.js

import { useRef, useEffect } from "react";
import ReactDOM from "react-dom/client";
import "./myStyles.css";

const PrintableComponent = (props) => {
  return (
    <div>
      <h1>Images in HTML</h1>

      <img
        height={200}
        width={250}
        src="https://i.natgeofe.com/k/c9d2cffc-2152-404a-b540-1cc48bbcd3f2/spinosaurid-dino-news.jpg"
        alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"
        title="A T-Rex on display in the Manchester University Museum"
      />
      <blockquote>
        <p>
          But down there it would be dark now, and not the lovely lighted
          aquarium she imagined it to be during the daylight hours, eddying with
          schools of tiny, delicate animals floating and dancing slowly to their
          own serene currents and creating the look of a living painting. That
          was wrong, in any case. The ocean was different from an aquarium,
          which was an artificial environment. The ocean was a world. And a
          world is not art. Dorothy thought about the living things that moved
          in that world: large, ruthless and hungry. Like us up here.
        </p>
        <footer>
          - Rachel Ingalls, <cite>Mrs. Caliban</cite>
        </footer>
      </blockquote>
    </div>
  );
};

function MyComponent() {
  let printRef = useRef(null);

  useEffect(() => {
    var beforePrint = function () {
      console.log("Component rendering started : Beforeprint.");

      printRef = ReactDOM.createRoot(document.getElementById("print-mount"));
      printRef.render(<PrintableComponent />);

      console.log("Component rendering ended : Beforeprint.");
    };

    var afterPrint = function () {
      console.log("Component cleaning started : Afterprint");

      if (printRef) printRef.unmount();

      console.log("Component cleaning ended : Afterprint");
    };

    if (window.matchMedia) {
      var mediaQueryList = window.matchMedia("print");
      mediaQueryList.addEventListener("change", function (mql) {
        if (mql.matches) {
          beforePrint();
        } else {
          afterPrint();
        }
      });
    }

    //Alternate option of matchMedia() query.
    // window.onbeforeprint = beforePrint;
    // window.onafterprint = afterPrint;
  }, []);

  const handlePrint = () => {
    printRef = ReactDOM.createRoot(document.getElementById("print-mount"));
    printRef.render(<PrintableComponent />);

    //Just give some time to render component
    setTimeout(() => {
      window.print();
    }, 5);
  };

  return (
    <div className="hideContent">
      <h2>Let's get started!</h2>
      <button onClick={handlePrint}>Print</button>
    </div>
  );
}

export default MyComponent;

myStyle.css

@media print {
  .hideContent {
    display: none;
  }
}

This guide explores secure and effective ways to print from your React applications, without using any third party library. We’ll focus on reliable methods that prioritize security and browser compatibility. Please download complete code here, React Printing Code.

Leave a Reply

Your email address will not be published. Required fields are marked *