I’m trying to print specific components of my app using react-to-print library. I’m trying to override the event of pressing ctrl+p
for printing by using event.preventDefault()
and it’s working for the first time that is when the app renders, on ctrl+p the required components are getting printed but after this the second time I click ctrl+p is not getting caught inside my handleKeyDown
function, instead the browser default of printing the entire page is happening.
import React, { useCallback, useEffect, useRef } from "react";
import { useReactToPrint } from "react-to-print";
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
const handleKeyDown = useCallback(
(event) => {
console.log("keydown");
if (event.ctrlKey && event.key === "p") {
event.preventDefault();
handlePrint();
}
},
[handlePrint]
);
useEffect(() => {
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [handleKeyDown]);
return (
<div>
<div ref={componentRef}>
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
</div>
<div>Div not printed</div>
<button onClick={handlePrint}>Print this out!</button>
</div>
);
};
export default Example;
The ctrl+p gives the desired result the first time after every re-render but on further tries its not working. I’m assuming the issue to be with the keyDown
event not getting caught after causing the print for the first time.