Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.
Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:
https://mcmap.net/q/413315/-how-to-print-react-component-on-click-of-a-button
This is what the component ended up looking like. It prints everything in the body of the modal.
import React, { Component } from 'react';
import {
Button,
Modal,
ModalBody,
ModalHeader
} from 'reactstrap';
export default class TestPrint extends Component{
constructor(props) {
super(props);
this.state = {
modal: false,
data: [
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test'
]
}
this.toggle = this.toggle.bind(this);
this.print = this.print.bind(this);
}
print() {
var content = document.getElementById('printarea');
var pri = document.getElementById('ifmcontentstoprint').contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
}
renderContent() {
var i = 0;
return this.state.data.map((d) => {
return (<p key={d + i++}>{i} - {d}</p>)
});
}
toggle() {
this.setState({
modal: !this.state.modal
})
}
render() {
return (
<div>
<Button
style={
{
'position': 'fixed',
'top': '50%',
'left': '50%',
'transform': 'translate(-50%, -50%)'
}
}
onClick={this.toggle}
>
Test Modal and Print
</Button>
<Modal
size='lg'
isOpen={this.state.modal}
toggle={this.toggle}
className='results-modal'
>
<ModalHeader toggle={this.toggle}>
Test Printing
</ModalHeader>
<iframe id="ifmcontentstoprint" style={{
height: '0px',
width: '0px',
position: 'absolute'
}}></iframe>
<Button onClick={this.print}>Print</Button>
<ModalBody id='printarea'>
{this.renderContent()}
</ModalBody>
</Modal>
</div>
)
}
}
Note: However, I am having difficulty getting styles to be reflected in the iframe
.