Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-to-print

MatthewHerbst3mMIT3.1.1TypeScript support: included

Print React components in the browser

react, print, reactjs, react-to-print

readme

react-to-print logo

ReactToPrint - Print React components in the browser

NPM Downloads npm version

Print the content of a React component.

npm install --save react-to-print

Demo

Run react-to-print

Usage

import { useReactToPrint } from "react-to-print";
import { useRef } from "react";

const contentRef = useRef<HTMLDivElement>(null);
const reactToPrintFn = useReactToPrint({ contentRef });

return (
  <div>
    <button onClick={reactToPrintFn}>Print</button>
    <div ref={contentRef}>Content to print</div>
  </div>
);

It is also possible to lazy set the ref if your content being printed is dynamic. See the LazyContent example for more. This can also be useful for setting the ref in non-React code, such as util functions.

API

Option Type Description
bodyClass string One or more class names to pass to the print window, separated by spaces
contentRef React.RefObject<Element | Text> The ref pointing to the content to be printed. Alternatively, pass the ref directly to the callback returned by useReactToPrint
copyShadowRoots boolean Copy shadow root content into the print window. Warning: Use with care if you print large documents as traversing these can be slow.
documentTitle string Set the title for printing when saving as a file
fonts { family: string, source: string; weight?: string; style?: string; }[] A list of fonts to load into the printing iframe. This is useful if you are using custom fonts
ignoreGlobalStyles boolean Ignore all <style> and <link type="stylesheet" /> tags
nonce string Set the nonce attribute for allow-listing script and style elements for Content Security Policy (CSP)
onAfterPrint () => void Callback function that triggers after the print dialog is closed regardless of if the user selected to print or cancel
onBeforePrint () => Promise<void> Callback function that triggers before print. This can be used to change the content on the page before printing as an alternative to, or in conjunction with, @media print queries
onPrintError (errorLocation: 'onBeforePrint' | 'print', error: Error) => void Called if there is a printing error serious enough that printing cannot continue. Currently limited to Promise rejections in onBeforePrint, and print.
pageStyle string react-to-print sets some basic styles to help improve page printing, notably, removing the header and footer that most browsers add. Use this to override these styles and provide your own
preserveAfterPrint boolean Preserve the print iframe after printing. This can be useful for debugging by inspecting the print iframe
print (iframe: HTMLIFrameElement) => Promise<void> If passed, this function will be used instead of window.print to print the content. Use this to print in non-browser environments such as Electron
suppressErrors boolean When passed, prevents console logging of errors

Compatibility

react-to-print should be compatible with most modern browsers.

Mobile Browsers in WebView

While printing on mobile browsers generally works, printing within a WebView (when your page is opened by an app such as Facebook or Slack, but not by the full browser itself) is known to generally not work. Some WebViews don't make the correct API available. Others make it available but cause printing to no-op.

We are actively researching resolutions to this issue, but it likely requires changes by Google/Chromium and Apple/WebKit. See #384 for more information. If you know of a way we can solve this your help would be greatly appreciated.

Known Incompatible Browsers

Known Issues

  • Some mobile browser may, instead of printing, open the native Share action instead
  • onAfterPrint may fire immediately (before the print dialog is closed) on newer versions of Safari where window.print does not block
  • (401): TypeScript errors such as Type 'undefined' is not assignable to type 'ReactInstance | null'.. You likely need to set your ref to initially be null: useRef(null)

Common Pitfalls

  • documentTitle will not work if react-to-print is run within an iframe. If react-to-print is run within an iframe and your script has access to the parent document, you may be able to manually set and then restore the parent document's title during the print. This can be done by leveraging the onBeforePrint and onAfterPrint callbacks.

  • When printing, only styles that directly target the printed nodes will be applied as the parent nodes of the printed nodes will not exist in the print DOM. For example, in the code below, if the <p> tag is the root of the ComponentToPrint then the red styling will not be applied. Be sure to target all printed content directly and not from unprinted parents.

    <div className="parent">
      <p>Hello</p>
    </div>
    div.parent p { color:red; }
  • The connect method from react-redux returns a functional component that cannot be assigned a reference to be used within the contentRef. To use a component wrapped in connect within contentRef, create an intermediate component that simply renders your component wrapped in connect. See 280 for more.

  • When rendering multiple components to print, ensure each is passed a unique ref. Then, either use a unique useReactToPrint call for each component, or, using a single useReactToPrint call pass the refs at print-time to the printing function returned by the hook. If you share refs across components only the last component will be printed. See 323 for more.

FAQ

How can content be hidden/shown during printing?

The simplest way to hide or show content during printing is to use a CSS Media Query.

.printContent {
  display: none;

  @media print {
    display: block;
  }
}
const contentRef = useRef<HTMLDivElement>(null);
const reactToPrintFn = useReactToPrint({ contentRef });

return (
  <div>
    <button onClick={reactToPrintFn}>Print</button>
    <div className="printContent" ref={contentRef}>Content to print</div>
  </div>
);

Can react-to-print be used to download a PDF without using the Print Preview window?

Not directly. We aren't able to print a PDF as we lose control once the print preview window opens. However, it is possible to use react-to-print to gather the content you want to print and pass it to a library that can generate a PDF.

const handlePrint = useReactToPrint({
  ...,
  print: async (printIframe: HTMLIframeElement) => {
    // Do whatever you want here, including asynchronous work
    await generateAndSavePDF(printIframe);
  },
});

For examples of how others have done this, see #484

Can react-to-print be used to change the settings within the print preview dialog?

No. The window.print API does not provide a way to change these settings. Only various CSS hints can be provided, with each browser potentially treating them differently.

Can the ComponentToPrint be a Class component?

Not directly. To print a Class based component you will need to manually forward the contentRef as a prop:

class ComponentToPrint extends Component {
  render() {
    return (
      <div ref={this.props.innerRef}>
        Print content
      </div>
    )
  }
}

function App {
  const contentRef = useRef(null);
  const handlePrint = useReactToPrint({ contentRef });

  return (
    <div>
      <button onClick={handlePrint}>Print</button>
      <ComponentToPrint innerRef={contentRef} />
    </div>
  );
}

Why does onAfterPrint fire even if the user cancels printing

onAfterPrint fires when the print dialog closes, regardless of why it closes. This is the behavior of the onafterprint browser event.

<link>s with empty href attributes are invalid HTML. In addition, they can cause all sorts of undesirable behavior. For example, many browsers - including modern ones, when presented with <link href=""> will attempt to load the current page. Some even attempt to load the current page's parent directory.

Note: related to the above, img tags with empty src attributes are also invalid, and we may not attempt to load them.

How do you make ComponentToPrint show only while printing

If you've created a component that is intended only for printing and should not render in the parent component, wrap that component in a div with style set to { display: "none" }, like so:

<div style={{ display: "none" }}><ComponentToPrint ref={componentRef} /></div>

This will hide ComponentToPrint but keep it in the DOM so that it can be copied for printing.

Setting state in onBeforePrint

Recall that setting state is asynchronous. As such, you need to pass a Promise and wait for the state to update.

const [isPrinting, setIsPrinting] = useState(false);
const contentRef = useRef(null);

// We store the resolve Promise being used in `onBeforePrint` here
const promiseResolveRef = useRef(null);

// We watch for the state to change here, and for the Promise resolve to be available
useEffect(() => {
  if (isPrinting && promiseResolveRef.current) {
    // Resolves the Promise, letting `react-to-print` know that the DOM updates are completed
    promiseResolveRef.current();
  }
}, [isPrinting]);

const handlePrint = useReactToPrint({
  contentRef,
  onBeforePrint: () => {
    return new Promise((resolve) => {
      promiseResolveRef.current = resolve;
      setIsPrinting(true);
    });
  },
  onAfterPrint: () => {
    // Reset the Promise resolve so we can print again
    promiseResolveRef.current = null;
    setIsPrinting(false);
  }
});

Note: for Class components, pass the Promise resolve to the callback for this.setState: this.setState({ isPrinting: false }, resolve)

Changing print settings in the print dialog

Unfortunately there is no standard browser API for interacting with the print dialog. All react-to-print is able to do is open the dialog and give it the desired content to print. We cannot modify settings such as the default paper size, if the user has background graphics selected or not, etc.

Printing video elements

react-to-print tries to wait for video elements to load before printing but a large part of this is up to the browser. Further, the image displayed will usually be the first frame of the video, which might not be what you expect to show. To ensure the proper image is displayed in the print we highly recommend setting the poster attribute of the video, which allows specifying an image to be a placeholder for the video until the video loads.

Electron

react-to-print can be used for printing in Electron, but you will need to provide your own print method since Electron does not natively support the window.print method. Please see this answer on StackOverflow for how to do this.

There is a fully-working example of how to use react-to-print with Electron available here.

Some frameworks such as Ruby on Rails will set media="screen" on <link> elements that don't have screen set. This can cause styles to appear incorrectly when printing. To fix, explicitly set media="screen" on your <link> elements. For <link> elements meant to apply only when printing, set media="print".

Helpful Style Tips

Set the page orientation

While you should be able to place these styles anywhere, sometimes the browser doesn't always pick them up. To force orientation of the page you can include the following in the component being printed:

<style type="text/css" media="print">{"\
  @page {\ size: landscape;\ }\
"}</style>

Set the page size

The default page size is usually A4. Most browsers do not allow JavaScript or CSS to set the page size. For the browsers that do, it is usually done using the CSS page size property. Check caniuse to see if the browsers you develop against support this.

@media print {
  @page {
    size: 50mm 150mm;
  }
}

Set custom margin to the page (29)

To set custom margin to the page,

First, create a function to return the page margin,

const getPageMargins = () => {
  return `@page { margin: ${marginTop} ${marginRight} ${marginBottom} ${marginLeft} !important; }`;
};

Now, within the JSX call this function within the style tags,

<style>{getPageMargins()}</style>

PS: This style tag should be inside the component that is being passed in as the content ref.

Set landscape printing (240)

In the component that is passed in as the content ref, add the following:

@media print {
  @page { size: landscape; }
}

Printing elements that are not displayed (159)

Instead of using { display: 'none'; }, try using { overflow: hidden; height: 0; }

Using pageStyle

pageStyle should be a CSS string. For example: ".divider { break-after: always; }"

Getting a blank page when printing

Many have found setting the following CSS helpful. See #26 for more.

@media print {
  html, body {
    height: 100vh; /* Use 100% here to support printing more than a single page*/
    margin: 0 !important;
    padding: 0 !important;
    overflow: hidden;
  }
}

Another thing to try, especially if you are seeing this issue on mobile browsers, is to set preserveAfterPrint: true as it's possible the browser is causing the print iframe to be removed before printing has completed.

Styles incorrect in print dialog when using grid system

We often (#327, #343, #382) see issues reported where the developer is using Bootstrap or a similar grid system, and everything works great until the user goes to print and suddenly it seems the styles are off. We've found that often the issue is the grid library uses the smallest sized columns during printing, such as the xs size on Bootstrap's grid, a size developers often don't plan for. The simplest solution is to ensure your grid will adapt to this size appropriately, though this may not be acceptable since you may want the large view to print rather than the smaller view. Another solution is to override the grid column definition. Some newer versions of libraries have specific tools for dealing with printing, for example, Bootstrap 4's Display property.

Page Breaks

What to know:

Pattern for Page-Breaking Dynamic Content

Define a page-break class to apply to elements which could be sensibly split into a page.

<div className="print-container" style={{ margin: "0", padding: "0" }}>
  {listOfContent.map(yourContent => (
    <>
      <div className="page-break" />
      <div>{yourContent}</div>
    </>
  ))}
</div>

In your styles, define your @media print styles, which should include setting your preference for CSS page-break- (see w3's reference for options) to auto, and ensuring that your page-break element does not affect non-print styles.

@media all {
  .page-break {
    display: none;
  }
}

@media print {
  html, body {
    height: initial !important;
    overflow: initial !important;
    -webkit-print-color-adjust: exact;
  }
}

@media print {
  .page-break {
    margin-top: 1rem;
    display: block;
    page-break-before: auto;
  }
}

@page {
  size: auto;
  margin: 20mm;
}

Troubleshooting Page Breaks

If your content rendered as print media does not automatically break multi-page content into multiple pages, the issue may be

  • Style incompatibilities with print media rendering
  • A need to assign CSS page-break- properties to define how your document should behave when printed

Common Page Break Pitfalls

  • A style of overflow: scroll, when rendered to print, will result in cut off content instead of page breaks to include the content
  • A style of position: absolute, when rendered to print, may result in reformatted, rotated, or re-scaled content, causing unintended affects to print page layout and page breaks
  • Using flex may interfere with page breaks, try using display: block

Handling Scrolling (603)

Edit react-to-print (Handling Scrolling)

If you need to print the content of a scrolling container, you may encounter the following issues:

To solve these problems, you need to modify the properties of the scrolling container when printing. You can pass a function to the print property, which will be called when printing. In this function, you can use the DOM API to query the scrolling container that needs to be modified, and then modify its properties to control the scroll position.

const customToPrint = (printWindow) => {
  const printContent = printWindow.contentDocument || printWindow.contentWindow?.document;
  const printedScrollContainer = printContent.querySelector('.scroll-container');

  const originScrollContainer = document.querySelector('.scroll-container');

  // Set the scroll position of the printed container to match the origin container
  printedScrollContainer.scrollTop = originScrollContainer.scrollTop;

  // You can also set the `overflow` and `height` properties of the printed container to show all content.
  // printedScrollContainer.style.overflow = "visible";
  // printedScrollContainer.style.height = "fit-content";

  printWindow.contentWindow.print();
}

const handlePrint = useReactToPrint({
  // ...
  print: customToPrint,
});

Simple Show All Content

In addition to the methods in the above example, you can also simply add a CSS class name to the scrolling container when printing to show all content.

Set the container to overflow: visible; height: fit-content when printing, cancel the scrolling behavior when the content overflows, and make the height adapt to the content.

@media print {
  .scroll-container {
    overflow: visible;
    height: fit-content;
  }
}

Note:

  • If the styles do not take effect, you can try using the !important modifier.
  • The styles provided in the above instructions are for reference only. Complex situations may require more styles to achieve the desired result.

Running locally

NOTE: The library is built and tested locally using Node ^20.

  • Clone the repo
  • npm ci
  • npm start

changelog

CHANGELOG

3.1.1 (June 30th, 2025)

  • FIX 812: Better detect optional lazy content versus Event
  • CHORE 813: Upgrade all devDependencies

3.1.0 (April 27th, 2025)

  • FIX 804: Correct issues with onBeforePrint
  • FEAT 803: Allow passing the useReactToPrint callback directly to event handlers

3.0.6 (March 28th, 2025)

  • CHORE 794: Improve memoization of options passed to react-to-print. Thanks FatahChan

3.0.5 (January 27th, 2025)

  • FIX 779: Fix a bug causing onAfterPrint to not always fire when the print window closes. Thanks sensasi-delight

3.0.4 (December 24th, 2024)

  • FIX 772: Ensure that video elements with an empty src attribute do not prevent printing from continuing. Thanks @Can-Chen

3.0.3 (December 22th, 2024)

  • FIX 764: Ensure onAfterPrint is called, and print iframe is removed, after the print preview dialog has closed. Previously these would happen when the afterprint event was received which, as noted in the README, may occur immediately in some browsers, rather than when the print preview dialog closes. Thanks sensasi-delight
  • FIX 768: React 19 made a small change to the typing for Refs which requires explicitly handling null/undefined initial types
  • CHORE: Minor code cleanup and comments
  • CHORE: Updated devDependencies to latest, including now using React 19 for our examples
  • DOCS: README updates, including a link to using the lazy method of providing content

Beta Versions

  • 3.0.3-beta-1 (16th Dec 2024)

3.0.2 (October 17th, 2024)

  • FIX 751: Ensure selected <select> option printed. Currently the first option is printed regardless of selection state
  • FIX 753: Fix incorrect ESLint config reference to tsconfig file

3.0.1 (September 30th, 2024)

  • FIX 743: Allow passing the function returned from useReactToPrint directly to event handlers (this is primarily geared at non-typescript users who are not aware of the new v3 API that prefers the function be wrapped, by changing onClick={printFn} to onClick={() => printFn()})

3.0.0 (September 28th, 2024)

v3.0.0 brings API modernization, React 19 support, a smaller package size, Shadow DOM support, and improved error handling.

BREAKING CHANGES

  • content renamed to contentRef and type changed from () => React.ReactInstance to RefObject<Element | Text>. The core impact here is that Class components now need to have the ref forwarded via props internally to a DOM node
  • React >= 16.8.0 required (dropped support for React versions that don't support hooks)
  • onBeforeGetContent removed. Use onBeforePrint, which similar to onBeforeGetContent, now runs before the print iframe is loaded
  • removeAfterPrint renamed to preserveAfterPrint which defaults to false
  • ReactToPrint removed. Use useReactToPrint
  • PrintContextConsumer removed. Use useReactToPrint
  • trigger removed, use the function returned by useReactToPrint
  • IReactToPrintProps renamed to UseReactToPrintOptions
  • Default package export removed, use named useReactToPrint export
  • Removed event?: unknown type from useReactToPrint callback. optionalContent is now the only (optional) argument
  • Build is now ES6 code. Previously it was ES5
  • No longer supporting IE11

New

  • FEATURE 717: React 19 support + API modernization
  • FEATURE 707: Improved error handling when canvas elements have not properly loaded
  • FEATURE 723: Add new option, copyShadowRoots, to support copying ShadowRoots. Thanks boehlke
  • CHORE: package size reduced by 18.7kb (34%)
  • CHORE: dev dependencies updated

Beta Versions

  • 3.0.0-beta-3 (19 Aug 2024)
  • 3.0.0-beta-2 (19 Aug 2024)
  • 3.0.0-beta-1 (15 Jul 2024)

2.15.1 (February 13th, 2024)

  • FIX 686 A breaking type error was mistakenly introduced as part of 652. This has been fixed.

2.15.0 (February 11th, 2024)

  • FEATURE 652: When using the useReactToPrint hook it is now possible to pass the returned callback the content ref at call time, rather than needing to pass it to the hook directly. This allows for generating the content to be printed closer to when the print occurs. Thanks isocroft
  • DEPENDENCIES: Upgraded all devDependencies to their latest versions
  • CHORE: broke up the single file in the repo, started organizing things a bit

2.14.15 (October 2nd, 2023)

This is a republish of 2.14.14 since that version got screwed up by some downtime at npm and seems to be in an unrecoverable state.

2.14.14 (September 22nd, 2023)

  • FIX 635: Ensure proper handling of <link> nodes that have multiple value rel attributes set such as rel="prefetch stylesheet", and, ensure proper handling of <link> nodes using rel="preload" + as="style"
  • DOCS 637: Added README section regarding having proper a media attribute set on <link> nodes
  • DOCS 633 Added README section regarding proper printing of scrolled containers. Thanks siaikin!
  • DEPENDENCIES: Upgrade all devDependencies to their latest versions

2.14.13 (June 7th, 2023)

  • FIX 616: When passing a custom print function we were not waiting for that function to resolve its promise before removing the printing iframe if removeAfterPrint={true} was set. Further, we were not calling onAfterPrint at all when a custom printing function was passed. While not strictly needed since the caller knows when the printing has completed by resolving the promise, we now call onAfterPrint when that promise has resolved and before removing the print iframe
  • DEPENDENCIES: Removed our long unused single prod dependency, prop-types. The package now has zero dependencies 🪓
  • CHORE: Updated all devDependencies to their latest versions
  • CHORE: Removed a bunch of old unused files including require.d.ts, .babelrc, and an unused example

2.14.12 (February 18th, 2023)

  • FIX 565: Support font-weight and font-style for custom fonts (and add more font examples). Thanks gauthierrodaro
  • CHORE: Updated all devDependencies

2.14.11 (January 3rd, 2023)

Happy new year! We can't wait to see what 2023 brings

  • FIX: Ensure we wait for fonts to print if they are given
  • FIX: Ensure we continue trying to print when fonts are passed by the browser doesn't support the FontFace API
  • FIX: Improved chances of FireFox printing backgrounds by default in the Print Preview window
  • FIX: Ensure we only process resources once
  • CHORE: Simplified loading logic, including improved error messages when a resource fails to load
  • CHORE: Removed unused TravisCI config
  • CHORE: Updated all devDependencies
  • CHORE: License year updated for 2023 :)
  • DOCS: A bunch of examples and gotchas were added to the README, improved example

2.14.10 (November 17th, 2022)

  • FIX 556 In 2.14.9 we changed the print iframe size to be dynamic but didn't take into account the fixed offset we were giving to hide it on the page. This resulted in the print iframe being partially visible when printing on wide screens. This has been corrected

2.14.9 (November 14th, 2022)

  • FIX 553 Ensures that the iframe used for printing has the same viewport size as the parent window of the node being printed. Prior to this the browser set the default 300px/150px size on the iframe, causing code that changes styles based on viewport sizes (such as many grid systems) to sometimes change the display of the elements being printed, requiring CSS hacks to avoid. Thanks dantecarlo for reviving this issue

2.14.8 (November 3rd, 2022)

  • FIX 537/545 <link> nodes marked with the disabled attribute were causing printing to hang. Thanks luckrnx09
  • FIX/CHORE 545 Updated examples to use React 18. This also exposed a minor typing bug (ReactToPrint needed to specify a children prop to fully support React 18) which was corrected. Other dependencies were also updated, mostly dropping Node 12 support
  • CHORE 538 The examples had some minor Webpack related refactors

2.14.7 (April 28th, 2022)

  • FIX 484: Previously onAfterPrint was not being called if a custom print function was passed. Now it will always be called
  • CHORE: a couple devDependency updates to make npm audit happy

2.14.6 (April 9th, 2022)

  • FIX 485: react-to-print assumed that the tagName of <style> nodes was always 'STYLE', however, sometimes it can be 'style' or possibly other case combinations. Added resiliency to the check so now any casing of 'style' will pass the check

2.14.5 (March 31st, 2022)

  • FIX 479: React 18 is now a supported peerDependency. Thanks fabb

2.14.4 (January 24th, 2022)

  • FIX 459: react-to-print now ensures that a DOCTYPE is set on the print iframe. Without this some browsers could render the print iframe in quirks mode, possibly changing the output
  • CHORE: Removed some debugging statements that made it into a previous production build
  • CHORE: Updated all dependencies
  • DOCS: Added a section with a link to a fully-working Electron example

2.14.3 (December 25th, 2021)

  • FIX 439: react-to-print now waits for video elements to load before printing. While this should work in most cases, we highly recommend setting the poster attribute of the video, which allows specifying an image to be a placeholder for the video until the video loads.
  • CHORE: cleaned up the examples code a bit, including adding tests for video elements
  • CHORE: all devDependencies have been upgraded to their latest and greatest

Happy new years!

2.14.2 (December 14th, 2021)

  • FIX: As seen in 441 when using the useReactToPrint hook along with TypeScript and strict checking the user is currently required to ensure that the return of useReactToPrint isn't undefined, since that is what is returned if the user is using a version of React that does not support hooks. To remove the need for this check useReactToPrint will now return a function that throws an error if the version of React does not support hooks.

2.14.1 (November 21st, 2021)

  • FIX 429: Attempting to access the contents of a cross-origin stylesheet is forbidden by scripts, and attempting to do so would cause react-to-print to crash. Upstream work in the browsers is required to find a proper solution to this, read more in the issue. A try/catch has been added around the offending code, along with a warning message with tips on how to resolve. Thanks @JoshuaKGoldberg for lots of debugging help
  • FIX 432: TypeScript 4.4 shipped with FontFace support in its lib definitions which caused react-to-print to fail to build locally on versions of TypeScript >= 4.4 since our FontFace definitions clashed with those now in TypeScript. This has been resolved, thanks @oxygen-xx
  • DOCS 422: The README was updated to properly reflect that functional components can be used so long as they are wrapped with React.forwardRef
  • DOCS 430: A typo was fixed, thanks @hsusanoo

2.14.0 (October 20th, 2021)

  • FIX 391: Setting documentTitle will now properly set the filename when printing as a PDF in Chrome, Firefox, and Safari
  • FIX: a rare (no reported events) edge case could cause printing to hang if an image failed to load and error logging was not enabled. This has been fixed
  • FEATURE: the UI for running the examples has been massively improved. Try them out! We will be porting this to our official CodeSandbox example soon.
  • CHORE: changed an error message saying only class based components are allowed to be printed to clarify that functional components wrapped in React.forwardRef can be printed as well
  • CHORE: refactored logging code to be DRYer and simpler to use
  • CHORE: all devDependencies have been upgraded to their latest and greatest
  • DOCS: major improvements to the README, including making some examples more concise, adding information about using functional components to print, adding some new pitfalls, and adding information about known issues when printing in mobile WebViews (see #384 for more)

2.13.0 (August 4th, 2021)

2.12.6 (May 31st, 2021)

  • FIX 379: img tags missing a src attribute should not prevent printing

2.12.5 (May 29th, 2021)

  • CHORE: Upgraded devDependencies

2.12.4 (April 10th, 2021)

  • CHORE: Upgraded all devDependencies
  • DOCS: Added a section to the README about workarounds for functional components as the ComponentToPrint

2.12.3 (February 5th, 2021)

  • FIX 344: Remove the single use of ParentNode.append in favor of Node.appendChild. append is not supported by IE11, and polyfilling it within the context of an iframe can be difficult
  • FIX 344: While testing the above I realized that trying to print out a bare string didn't work. This has been fixed
  • CHORE: Upgraded all devDependencies

2.12.2 (January 1st, 2021)

Happy new years!

  • FIX 196: For a long time various inputs/select did not properly copy their value over into the print window. This has been corrected!
  • FIX 292: Removed usage of document.write
  • FIX: Edge case where passing a function to the pageStyle prop that did not return a string could cause problems
  • CHORE: Upgraded all devDependencies
  • CHORE: Minor README updates

2.12.1 (December 14th, 2020)

  • FIX 329: v2.12.0 upgraded Webpack from 4 -> 5 which broke the package for environments that didn't support ES6 as Webpack now requires finer grained controls to output pure ES5 code. These changes have been made.
  • CHORE: upgraded all devDependencies

2.12.0 (November 27th, 2020)

  • CHORE: added React/ReactDOM ^17 to allowed peerDependencies. Library still supports React >= 15, though expect a major release in the near-future that drops React 15 support, which will clear the way to removing the restriction that the top-level component being printed must be a class component
  • CHORE: upgraded all devDependencies. Big changes here include updating Typescript from 3 -> 4 and Webpack from 4 -> 5. While upgrading Webpack the minifier was changed from UglifyJS to Terser, resulting in a 5.7% reduced file size (14.1kb -> 13.3kb)
  • CHORE: Use Node ^14 for CLI tests
  • DOCUMENTATION: small improvements to the examples, including renaming them from example -> examples
  • DOCUMENTATION: added a note about finding the examples folder
  • DOCUMENTATION 311: small type fix, thanks nealeu
  • DOCUMENTATION: added a "Common Pitfalls" section to the README, starting with a note on using the library with a component wrapped in connect from react-redux

2.11.0 (October 30th, 2020)

  • FIX/FEATURE 285: Adds a new fonts prop which allows the passing of custom fonts. Previously custom fonts were not loaded into the print window
  • CHORE: update patch and minor devDependencies, dedupe, and audit fix

2.10.3 (October 16th, 2020)

  • FIX 301: Ensures the library works with modules that have a null prototype such as ES modules and SystemJS modules. Thanks joeldenning

2.10.2 (October 16th, 2020)

  • FIX 298: Fixes a long-standing issue of checkbox state not always copying properly into the print window. Thanks aviklai
  • CHORE: update patch and minor devDependencies, dedupe, and audit fix

2.10.1 (October 15th, 2020)

  • FIX 296: Ensure bodyClass can handle multiple class names instead of just a single class name. Thanks seanblonien
  • CHORE: update patch and minor devDependencies, dedupe, and audit fix

2.10.0 (August 23rd, 2020)

  • FEATURE 272: a new prop print has been added. This can be used to override the default browser Window.print. This can be useful if you want to print in an alternative environment such as Electron. As part of this change, onPrintError will now report if an error occurs in a passed in print method. Thanks to Ririshi for this idea
  • DOCS 269: added guidelines for how to achieve nice page breaks. Thanks hbrannan
  • CHORE 273: updated devDependencies, npm dedupe, npm audit fix

2.9.0 (June 2nd, 2020)

  • FEATURE 255: updated local development examples so that every use case is covered
  • FIX 255: onload event listener is now cleared after being called
  • FIX 255: useReactToPrint now properly sets defaultProps
  • CHORE 256: updated devDependencies to latest. This clears a high severity npm audit issue

2.8.0 (May 19th, 2020)

  • FEATURE 245: documentTitle prop can now be passed to set a default filename when the user is saving as a PDF. Thanks zb2oby
  • FEATURE 244: trigger is now an optional prop. To print without it we now offer two new options.

    PrintContextConsumer with a render-props pattern:

    import { PrintContextConsumer } from 'react-to-print';
    
    <ReactToPrint content={() => this.componentRef}>
      <PrintContextConsumer>
        {({ handlePrint }) => <button onClick={handlePrint}>Print this out!</button>}
      </PrintContextConsumer>
    </ReactToPrint>

    useReactToPrint for hook-based printing

    import { useReactToPrint } from 'react-to-print';
    
    const Example = () => {
      const componentRef = useRef();
      const handlePrint = useReactToPrint({ content: () => componentRef.current });
    
      return (
        <div>
          <ComponentToPrint ref={componentRef} />
          <button onClick={handlePrint}>Print this out!</button>
        </div>
      );
    };

    Huge thanks to vtsybulin for these fantastic additions.

  • CHORE: upgrade devDependencies to latest

2.7.0 (May 1st, 2020)

  • FEATURE 198: pageStyle prop can now be passed as a function. Thanks sergeyshmakov
  • FIX 218: Image duplication in Edge and IE. This should also fix 211 (slow performance with many images on the page). Thank you dioscarey for helping to get this pushed through
  • Fix 93: Check for existence of target.contentWindow.print
  • CHORE: updated an error message (see 96)
  • CHORE: updated all devDependencies to latest
  • CHORE: slightly decreased size of the build by better using UglifyJS
  • CHORE: enabled TypeScript strict mode
  • CHORE: added a "Compatibility" section to the README. Also moved some sections around and shortened the example
  • CHORE: improved browser built targets based on browserslist best practices

2.6.3 (March 9th, 2020)

  • FIX 227 Add a title to the print iframe to improve accessibility. Thanks invious

2.6.2 (March 8th, 2020)

  • FIX 224 Handle the content prop returning null. This is required for proper usage in TypeScript strict mode. Thanks a-sync

2.6.1 (March 3rd, 2020)

  • CHORE 220 Added suppressErrors documentation to the README

2.6.0 (March 3rd, 2020)

  • FEATURE 220 Adds a suppressErrors prop. When passed, console logging of errors is disabled. Thanks invious

2.5.1 (January 9th, 2020)

  • CHORE 208 Minor improvements to code comments, linting, and README

  • CHORE 207 Updated devDependencies

  • FIX 204: Ensure images are fully loaded before printing. Previously long-loading images might not be included in the print. This ensures that we wait for them to load, similar to how we wait for style sheets to load. Thanks nhanhuynh-agilityio

2.5.0 (October 16th, 2019)

  • FEATURE 172: Allow the trigger component to be a functional component. Previously, only class based components were allowed here. Thanks idanhaviv

  • FEATURE 172: Enable CSS HMR when running the local example build. Thanks idanhaviv

2.4.0 (August 27th, 2019)

  • FEATURE 161: add a new callback method onPrintError. This method is called when react-to-print catches a Promise rejection in either onBeforeGetContent or onBeforePrint. The API docs were also cleaned up to better explain which method to use when.

  • FEATURE 158/160: add new callback method onBeforeGetContent. Currently, onBeforePrint is called before the print window is opened but after react-to-print has gathered the content of the page. This new method is fired before react-to-print gathers the content of the page, meaning it can be used to change the content of the page before printing. It can optionally return a Promise. Thanks @andfs

2.3.2 (August 6th, 2019)

  • CHORE 156: dependency upgrades. All listed dependencies were manually upgraded to their latest versions. npm audit fix was then run to give us a clean audit. Finally, npm dedupe was run to reduce package bloat.

  • FIX 156: a stylesheet that no longer exists but that was being required by the local example has been removed

NOTE: To build the library locally, Node ^8.6 is now required

2.3.1 (August 6th, 2019)

  • FIX 154: TSLint was not working properly for the project. A configuration was added, and linting errors were fixed. While fixing linting errors, a bug was discovered whereby if a stylesheet was found that did not have tag type STYLE it was possible that react-to-print would not include all stylesheets from the page into the print window

  • FIX: 154 (meant to be a different PR, was included by mistake in 154): When passing removeAfterPrint some users were getting the error TypeError: Object doesn't support property or method 'remove'. This was due to using an incorrect way to remove the iframe

2.3.0 (July 30th, 2019)

  • FEATURE 152: Previously, this library used a window rather than an iframe to handle printing. That was changed some time ago, however, the closeAfterPrint prop was never removed from the documentation (though it was removed from the code). This release restores similar functionality, in a new removeAfterPrint prop. Passing this prop will ensure that react-to-print removes the iframe it uses to print from the DOM after printing (something that it currently does not do). NOTE: the iframe is removed after the call to onAfterPrint (if provided) has completed. We will likely make this the default functionality in version 3, but are keeping it like this for now to ensure anyone relying on the iframe does not face issues. Thanks aviklai

2.2.1 (July 22nd, 2019)

  • FIX 149: Print window would not open if onBeforePrint was not given. Thanks aviklai

2.2.0 (July 19th, 2019)

  • FEATURE 140: onBeforePrint can now optionally return a Promise. If a Promise is returned, react-to-print will wait for it to resolve before continuing with the print. NOTE: react-to-print does not handle if the Promise rejects, so this must be accounted for when using this option. Thanks aviklai

2.1.3 (June 22nd, 2019)

  • FIX 134: Solve print window issues in Safari (especially Mobile Safari), thanks Ellenergic
  • CHORE: Updated the README to contain a link to a fully updated demo

2.1.2 (May 3rd, 2019)

  • FIX 118: Ensure fonts have time to load before printing, thanks aviklai

2.1.1 (April 13th, 2019)

  • FIX: Ensure we build the package as UMD instead of CommonJS (#116, thanks @aviklai)
  • CHORE: Added a CHANGELOG

2.1.0 (April 2nd, 2019)