DEV Community

Cover image for How to use react-to-print in react.js
ASAP_A1
ASAP_A1

Posted on

How to use react-to-print in react.js

Hi, y'all this is probably the simplest way to go when you're trying to add a download page functionality in react.

In this article, I'll be showing you how to implement pdf downloads from your react project using either class or functional components.

Installations

I assume you have your react project installed.

Now go ahead and add the packages

yarn add react-to-print
Enter fullscreen mode Exit fullscreen mode

or

npm i react-to-print
Enter fullscreen mode Exit fullscreen mode

Using functional components

Now we can go to our App.js component or any file you intend to use and import your package like so.

import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';

const App = () => {
  const componentRef = useRef();

  return (
    <div>
      <div ref={componentRef}>This contains all the files you intend to export[download]</div>
      <ReactToPrint
        trigger={() => <button>Print this out!</button>}
        content={() => componentRef.current}
      />
    </div>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

Voila! However, you might want to be passing the component from another file, then you'll have to pass the ref as a prop.

Using class component

Following the same method as the first approach, go to your desired file and follow the technique below.

import React from "react";
import ReactToPrint from "react-to-print";

class App extends React.Component {
  render() {

    return (
      <div>
        <div ref={(refer) => (this.componentRef = refer)}>Export my HTMl component to a PDF File</div>

        <ReactToPrint
          content={() => this.componentRef}
          trigger={() => (
            <button className="btn btn-primary">Print to PDF!</button>
          )}
        />
      </div>
    );
  }
}

export default Appp;
Enter fullscreen mode Exit fullscreen mode

Note when using an external file you'll just have to pass the ref directly into the component you're calling like so <ImportedComponent ref={(response) => (this.componentRef = response)} /> and yeah you're all good to go.

You're welcome.

Top comments (0)