0

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?

1
  • Did you manage to find a solution? Commented Sep 18, 2022 at 18:46

2 Answers 2

2

Yes, you can just use the React Hook forwardRef.

To build on the previous answer, here's the two files in question:

Example.js

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

import { ComponentToPrint } from './ComponentToPrint';

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

  const [text, setText] = useState('Hello world!');

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

Your React Function component to Print:

ComponentToPrint.js

import { forwardRef } from 'react';

const ComponentToPrint = forwardRef(( props, ref ) => {
  return (
  <div ref={ref}>
    <p>{props.text}</p>
  </div>
)});

export default ComponentToPrint;
Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );
};

1 Comment

My ComponentToPrint is also a functional component, will this solution work there too? Like can we set ref attribute in a functional component there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.