Answer the question
In order to leave comments, you need to log in
Print React Component?
It is necessary to send the component for printing by pressing the button. Tried doing it with react-to-print . Everything worked out, but only with a test example (in which a link is added at the top of the page, when clicked, the component goes to print).
The problem is that the button is in a Footer component. Tried to do like this:
To check if the button is pressed, but gottrigger={() => (this.state.isPrint)}
import ReactToPrint from 'react-to-print';
class ReportPage extends Component {
constructor(props) {
super(props);
this.state = {
isPrint: false
};
...
}
...
printTable(value) {
this.setState({ isPrint: value });
}
render() {
return (
<div>
<ReactToPrint
trigger={() => <a href='#'>Print this out!</a>} // здесь добавляется ссылка, при нажатии компонент уходит на печать
content={() => this.componentRef}
/>
<main>
...
<ReportTable ref={el => (this.componentRef = el)} /> // этот компонент надо напечатать
</main>
<Footer handlePrintTable={this.printTable}/>
</div>
);
}
}
class Footer extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.handlePrintTable(true);
}
render() {
return (
<footer>
...
<a href='#' role='button' onClick={this.handleClick}>
Распечатать
</a>
...
</footer>
);
}
}
Answer the question
In order to leave comments, you need to log in
I did it simply: I created styles for the print mode, and when I clicked on the button, I called window.print. And in my styles, depending on the active components, some were assigned display: none, and some changed their layout and colors. No third-party components were required in the end.
<div
onClick={() => {
if (!this.componentRef) {
return;
}
const mywindow = window.open('', 'PRINT');
if (!mywindow) {
return;
}
mywindow.document.write(
'<html><head><title>' + document.title + '</title>',
);
mywindow.document.write('</head><body >');
mywindow.document.write(this.componentRef.innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}}
>
Test
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question