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?
2 Answers
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;
Comments
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
Sujith Elango
My ComponentToPrint is also a functional component, will this solution work there too? Like can we set ref attribute in a functional component there?