1. header 요소의 높이를 가져옴 (없으면 0)
const headerHeight = document.querySelector("header")?.offsetHeight || 0;
2. .main-contents 요소의 상/하 패딩 값을 가져옴
- main-contents는 div의 className
const mainContentsPadding =
parseInt(getComputedStyle(document.querySelector(".main-container")!).paddingTop || "0", 10) +
parseInt(getComputedStyle(document.querySelector(".main-container")!).paddingBottom || "0", 10);
3. 남은 높이를 계산 (전체 창 높이 - 헤더 높이 - main-contents 패딩 - 100px)
const remainingHeight = (window.innerHeight - headerHeight - mainContentsPadding) - 100;
4. 상태 업데이트
- 상단에 useState 정의가 필요함
const [mainContentHeight, setMainContentHeight] = useState("auto");
- setMainContentHeight를 사용하여 재정의한 높이를 설정
setMainContentHeight(`${remainingHeight}px`);
5. 초기 실행 (마운트 시 한 번 실행)
updateMainContentHeight();
6. 창 크기가 변경될 때마다 updateMainContentHeight 실행
window.addEventListener("resize", updateMainContentHeight);
7. 컴포넌트가 언마운트될 때 이벤트 리스너 제거 (메모리 누수 방지)
return () => {
window.removeEventListener("resize", updateMainContentHeight);
};
8. 전체 코드
const [mainContentHeight, setMainContentHeight] = useState("auto");
useEffect(() => {
const updateMainContentHeight = () => {
const headerHeight = document.querySelector("header")?.offsetHeight || 0;
const mainContentsPadding =
parseInt(getComputedStyle(document.querySelector(".main-container")!).paddingTop || "0", 10) +
parseInt(getComputedStyle(document.querySelector(".main-container")!).paddingBottom || "0", 10);
const remainingHeight = (window.innerHeight - headerHeight - mainContentsPadding) - 100;
setMainContentHeight(`${remainingHeight}px`);
};
updateMainContentHeight();
window.addEventListener("resize", updateMainContentHeight);
return () => {
window.removeEventListener("resize", updateMainContentHeight);
};
}, []);
div에 style height 적용하면 끝
<div className="main-container" style={{ height: mainContentHeight }}>
'프로그래밍 언어 > React' 카테고리의 다른 글
[React] canvas 화면 캡쳐 후 이미지 저장(자동 다운로드) (0) | 2025.03.27 |
---|---|
[React] fetch 요청 두 번씩 되는 오류 (0) | 2025.03.13 |
[React] antd ant-design 504 (Outdated Optimize Dep) 오류 (0) | 2025.03.11 |
[React] lazy 코드 스플리팅 (0) | 2025.03.10 |
[React] 상태 관리 Redux 라이브러리 사용하여 slice, store, dispatch 설정 (0) | 2025.03.07 |