Sometimes, we want to print a React component on click of a button.
In this article, we’ll look at how to print a React component on click of a button.
How to print a React component on click of a button?
To print a React component on click of a button, we can use the react-to-print library.
To install it, we run:
npm i react-to-print
Then we write:
import React, { forwardRef, useRef } from "react";
import ReactToPrint, { PrintContextConsumer } from "react-to-print";
const ComponentToPrint = forwardRef((props, ref) => {
return <div ref={ref}>hello world</div>;
});
export default function App() {
const ref = useRef();
return (
<div>
<ReactToPrint content={() => ref.current}>
<PrintContextConsumer>
{({ handlePrint }) => (
<button onClick={handlePrint}>Print this out!</button>
)}
</PrintContextConsumer>
</ReactToPrint>
<ComponentToPrint ref={ref} />
</div>
);
}
to use it.
We wrap the component that triggers the opening of the print dialog in the PrintContextConsumer
.
And we wrap the PrintContextConsumer
with the ReactToPrint
component.
We set the content
prop to a function that returns the ref.current
value of the component we want to print when we click on the button.
We make the button open the print dialog by setting onClick
to handlePrint
.
Next, we set the ref
prop of the element we want to print as the value of the ref
prop.
Conclusion
To print a React component on click of a button, we can use the react-to-print library.