React-to-print: How to print child component without render it on parent component

Created on 15 May 2019  路  8Comments  路  Source: gregnb/react-to-print

My parent component is a table and it has many other components with a print button that generate report to print, the child component is a template of report. when I try to reference it<ReportTemplate ref={el => (this.componentRef = el)}/> it is rendered in Parent component. How can I pass the child component to <ReactToPrint/> without rendering it on parent component.

example

import ReportTemplate from './ReportTemplate';

class Report extends Component {
...

render() {
     return(
        <div>... </div> . <----- other child components
        <div>
            <ReactToPrint
                  trigger={() => <a href="#">Print this out!</a>}
                  content={() => this.componentRef}
            />
            <ReportTemplate ref={el => (this.componentRef = el)} /> . <--- ReportTemplate is rendering in parent component.
      </div>
    );
}
}

export default Report;
question

Most helpful comment

@FernandoLuizNemeChibli the style prop does not understand CSS, so values need to be strings:

style={{display:none}} -> style={{ display: 'none' }}

All 8 comments

<ReportTemplate ref={el => (this.componentRef = el)} /> 

to =>

<div style={{display:none}}>
     <ReportTemplate ref={el => (this.componentRef = el)} /> 
</div>
<ReportTemplate ref={el => (this.componentRef = el)} /> 

to =>

<div style={{display:none}}>
     <ReportTemplate ref={el => (this.componentRef = el)} /> 
</div>

I've tried your solution, but got an error instead:
'none' is not defined no-undef

here's my code:

<div>
  <ReactToPrint
    trigger={() => <Button >{t("Print Token")}</Button>}
    content={() => this.componentToPrint}
  />
  <div style={{display:none}}>
    <ResultAccessToken ref={el => (this.componentToPrint = el)} />
  </div>
</div>

@FernandoLuizNemeChibli the style prop does not understand CSS, so values need to be strings:

style={{display:none}} -> style={{ display: 'none' }}

@MatthewHerbst oh! now worked perfectly! thanks! (:
Thank you too, @lxx7061!

Actually, when I have more than 200 tables to print (each table per page), the <ReportTemplate ref={el => (this.componentRef = el)} /> make the parent component render too slow :( although I wrap a div to hide it <div style={{display:"none"}}></div>

Anyone suggest any solution ? I tried to use onBeforePrint to inject html then do the print, but it returns empty page, if I tried again then I can see the data =.=

Can I suggest adding this to the FAQ in the README?

@devuxer Sure! Mind making a PR for it?

@MatthewHerbst , Done!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JoshuaKGoldberg picture JoshuaKGoldberg  路  3Comments

invious picture invious  路  4Comments

abdurrehman1998 picture abdurrehman1998  路  8Comments

sprietNathanael picture sprietNathanael  路  4Comments

manfye picture manfye  路  5Comments