개발/🟦 React
ReactToPrint 특정 페이지 출력_리액트 라이브러리
비니_
2026. 1. 13. 11:05
728x90
react-to-print는 React 컴포넌트를 “프린트(출력)”하거나 PDF로 저장할 수 있게 도와주는 라이브러리
=> 화면에 보이는 특정 영역만 출력 가능~
=> React 컴포넌트 중 “원하는 영역만” 브라우저 출력/PDF로 만들기 위한 라이브러리
오 좋은디..?
1. 설치
// npm 사용
npm install react-to-print
// yarn 사용
yarn add react-to-print
2. 설치 확인
"dependencies": {
"react-to-print": "^2.x.x"
}
import ReactToPrint from 'react-to-print';
3. 기본 사용 구조
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
function MyPage() {
const printRef = useRef();
return (
<>
<ReactToPrint
trigger={() => <button>출력하기</button>}
content={() => printRef.current}
/>
<div ref={printRef}>
<h1>이 부분만 출력됨</h1>
<p>영수증 / 보고서 / 계약서</p>
</div>
</>
);
}
① useRef
=> 출력할 DOM 또는 컴포넌트 참조
② trigger
=> 클릭시 프린트가 되게 하는 부분 - 브라우저의 window.print() 실행
③ content
=> 출력 대상 ( 화면 전체 ❌, 지정한 영역만 ⭕)
❓ 라이브러리를 쓰는 이유 ❓
✔️ 기본 window.print() 문제점
- 페이지 전체 출력됨
- 레이아웃 깨짐
- 특정 영역만 출력하기 어려움
✔️ react-to-print 장점
- 특정 컴포넌트만 출력 가능
- React 구조 그대로 사용
- 프린트 전용 스타일 적용 쉬움
✔️👩💻 내 프로젝트에서 볼 수 있는 실전 예제
const componentRef = useRef(null);
<ReactToPrint
trigger={() => (
<Button type='button' className='btn_print'>
<Icon icon='LocalPrintshop' /> <span>{t('common.label.print')}</span>
</Button>
)}
content={() => componentRef.current}
onBeforeGetContent={(content) => {
setIsPrint(true);
return new Promise((resolve) => {
setTimeout(resolve, 10);
});
}}
onAfterPrint={() => {
setIsPrint(false);
}}
documentTitle={tr('titlePage')}
/>
<ApprovalContentsToPrint
printRef={componentRef}
/>
=> ⭐실행 해석 순서
1. trigger에 있는 .btn_print 버튼을 누르면 content={() => componentRef.current}가 실행되는데
2. componentRef를 가리키므로 참조하고 있는 DOM이 출력
3. printRef={componentRef}로 연결된 하단 ApprovalContentsToPrint 컴포넌트의 출력 영역 전체가 출력
728x90