Skip to content

Commit

Permalink
Handle hook fn being passed to event handlers raw (#743)
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewHerbst authored Sep 30, 2024
1 parent 670ad18 commit 2900c34
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 16 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ Print the content of a React component.

```tsx
const contentRef = useRef<HTMLDivElement>(null);
const handlePrint = useReactToPrint({ contentRef });
const reactToPrintFn = useReactToPrint({ contentRef });

return (
<div>
<button onClick={handlePrint}>Print</button>
<button onClick={reactToPrintFn}>Print</button>
<div ref={contentRef}>Content to print</div>
</div>
);
Expand Down
7 changes: 2 additions & 5 deletions examples/BasicComponent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,10 @@ export const BasicComponent = () => {
onBeforePrint: handleBeforePrint,
});

const handleOnClick = React.useCallback(() => {
printFn();
}, [printFn]);

return (
<div>
<button onClick={handleOnClick}>Print</button>
{/* @ts-expect-error Works without lazy content wrapping */}
<button onClick={printFn}>Print</button>
<ComponentToPrint ref={componentRef} />
</div>
);
Expand Down
8 changes: 0 additions & 8 deletions src/hooks/useReactToPrint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,6 @@ export function useReactToPrint(options: UseReactToPrintOptions): UseReactToPrin
return;
}

if (!contentNode) {
logMessages({
messages: ['"react-to-print" could not locate the DOM node corresponding with the `content` prop'],
suppressErrors,
});
return;
}

// NOTE: `canvas` elements do not have their painted images copied
// https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
const clonedContentNode = contentNode.cloneNode(true);
Expand Down
7 changes: 6 additions & 1 deletion src/utils/getContentNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ export function getContentNode({ contentRef, optionalContent, suppressErrors }:
});
}

return optionalContent();
// This check allows passing the callback from `useReactToPrint` directly into event
// handlers without having to wrap it in another function to capture the event
// See [#742](https://github.com/MatthewHerbst/react-to-print/issues/742) and [#724](https://github.com/MatthewHerbst/react-to-print/issues/724)
if (typeof optionalContent === "function") {
return optionalContent();
}
}

if (contentRef) {
Expand Down

0 comments on commit 2900c34

Please sign in to comment.