I want to print the page on a click, however I don't want to print the header and the button on the page:
<DetailedSummaryContainer id="detailedSummaryContainer">
{!this.state.printMode ?
<Header className="container">
<HeaderText>Header Text</HeaderText>
<ButtonContainer>
<StyledButton onClick={this.print}>Print</StyledButton>
</ButtonContainer>
</Header>
: null
}
<PrintableArea>
...
</PrintableArea>
</DetailedSummaryContainer>
So when clicked on Print, I want to change the printMode to true, so it rerenders the dom and then print the new dom, and then when the print preview is shown, and then I set the printMode to false again.
print = () => {
this.setState({ printMode: true }, () =>
{
console.log(this.state.printMode);
window.print();
});
}
For now I didn't set the printMode to false yet.
What happens with this code is that the state is changed to true, the page is rerendered and the header and button are not shown, but instead of opening a print preview a about:blank
new tab is opened.
The reason I want to keep the DetailedSummaryContainer
tag is I want the styles to be applied. Otherwise I would add a ref to PrintableArea
and do this:
print = () => {
var printContents = this.printComponent.innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
In this method the print works perfectly, but the style is only from PrintableArea
, I need the styles from DetailedSummaryContainer
to be applied too.
If there is a better way to do so, I can take another approach.
as per my comment:
you can put the ref on the DetailedSummaryContainer
instead of PrintableArea
since you're Header is null
when in printmode and not part of the innerHTML, so it's not conflicting with what you want and you get to keep the styling