Home > Software design >  Print a react functional component
Print a react functional component

Time:11-22

Hello everyone I have developed a react app using functional components and I need to print a particular page in the app. Since each page is a functional component, I thought maybe we could print a component separately. I tried using react-to-print but it supports only class components? Is this achievable through some NPM package?

CodePudding user response:

You can use react-to-print with functional component as it says in the FAQ's. Here is the example that they use on the npm website

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

import { ComponentToPrint } from './ComponentToPrint';

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

  return (
    <div>
      <ReactToPrint
        trigger={() => <button>Print this out!</button>}
        content={() => componentRef.current}
      />
      <ComponentToPrint ref={componentRef} />
    </div>
  );
};
  • Related