Notice
Recent Posts
Recent Comments
Link
250x250
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 아이콘사용법
- googleicon
- 웹아이콘
- package.json
- 의존성문제
- 동적객체
- 단어단위로떨어지기
- owlcarousel
- node설치
- XEIcon
- git lab clone
- minwidth
- node 오류
- 글자들여쓰기
- legacy-peer
- slickslider
- npm start
- npm install
- 정적객체
- 그누보드반응형
- maxwidth
- npm install 문제
- vscode git clone
- 플러그인
- fontawesome
- react npm install
- MediaQuery
- Git clone
- 이미지반응형
- window 정책변경
Archives
- Today
- Total
어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ
ReactToPrint 특정 페이지 출력_리액트 라이브러리 본문
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
'개발 > 🟦 React' 카테고리의 다른 글
| Popovers, usePopper 사용법, 공식문서 (0) | 2026.01.13 |
|---|---|
| 리액트에서 apiHelper.js 의 역할 (0) | 2026.01.13 |
| [FE] type.maybe, maybeNull (0) | 2026.01.07 |
| [FE] MST란? React_MobX State Tree (0) | 2026.01.07 |
| React useEffect로 body class넣기 / 리팩토링 (0) | 2026.01.06 |
Comments
