react-new-window
react-new-window copied to clipboard
Open window in print mode
Hi, I was wondering if it's possible to open a new window in print mode, with a print dialog box, using this library. Thanks,
I needed this same thing, but there's an escape hatch you can use. The <NewWindow/>
component attaches the window instance a class member called window
. To call the print method you can do the following:
- Attach a ref to your instance of the
<NewWindow/>
component. - If you are using a class component, then in your
componentDidUpdate
method you can call the print method like so:windowRef.window.print()
- If your are using a function component with hooks, attach a ref to the
<NewWindow/>
component, then create auseEffect
function like so:
useEffect(() => {
if(windowRef.current){
windowRef.current.window.print()
}
}, [windowRef.current])
not working for me @chrisjpatty
@Valerika i used @chrisjpatty 's hints this way:
<NewWindow ref={ref => (this.myRef = ref)}>
<SomeComponent newWindowRef={this.myRef} />
</NewWindow>
And within <SomeComponent />
:
handlePrint = () => {
this.props.newWindowRef.window.print()
}
There is another way. <NewWindow/>
has on undocumented property onOpen
that is passed a handle to the window.
The following worked for me
<NewWindow onOpen={win=>win.print()} >
<SomeComponent />
</NewWindow>
The onOpen
prop was added to the docs.